You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

C语言简易计算器除法(/)与取余(%)无输出且程序崩溃求助

解决你的C语言计算器闪退问题

嘿,作为刚入门C语言的新手,遇到这种问题太正常了——咱们一步步拆解代码里的坑,把除法和取余的闪退问题搞定~

核心问题拆解

你的程序在除法(/)和取余(%)时直接闪退,根源是输入输出格式不匹配导致的内存访问错误,具体看这几个关键点:

  • 取余(%)分支的错误

    1. 你用scanf("%f %f", &a, &b);读取数据,但abint类型,%f是给float/double用的格式符,强行把浮点数据塞进整数变量会直接破坏内存,触发崩溃。
    2. 取余运算符%要求两个操作数必须是整数,用%f输入完全没必要;而且后续printf里用%f输出int类型的abrem,格式不匹配也会引发异常。
  • 除法(/)分支的错误

    1. 同样犯了输入格式错误:用%f读取int变量,直接导致内存访问出错。
    2. 就算输入正常,a/b整数除法(因为两个操作数都是int),比如5/2会得到2而不是2.5,存到float里也还是2.0,不符合除法的预期结果。

修正后的完整代码

我把所有问题都修复了,还加了一些实用的防护逻辑,你可以直接运行试试:

// A simple calculator.
#include<stdio.h>
#include<conio.h>

void main() {
    int a, b, sum, diff, rem, multi;
    float div;
    char character;

    clrscr();
    printf("Choose the character you want to use(+, -, *, /, %%): ");
    // 加个空格吃掉之前的换行符,避免误读空字符
    scanf(" %c", &character);

    switch(character) {
        case '+': // Addition
            printf("Enter the first and second number: ");
            scanf("%d %d", &a, &b);
            sum = a + b;
            printf("The sum of %d and %d is %d\n", a, b, sum);
            break;
        case '-': // Subtraction
            printf("Enter the first and second number: ");
            scanf("%d %d", &a, &b);
            diff = a - b;
            printf("The difference between %d and %d is %d\n", a, b, diff);
            break;
        case '%': // Modulus
            printf("Enter the first and second number (integers only): ");
            // 用%d读取int类型变量
            scanf("%d %d", &a, &b);
            // 新增除数为0的判断,避免崩溃
            if(b == 0) {
                printf("Error: Cannot divide by zero for modulus!\n");
            } else {
                rem = a % b;
                // 用%d输出int类型结果
                printf("The remainder of %d divided by %d is %d\n", a, b, rem);
            }
            break;
        case '*': // Multiplication
            printf("Enter the first and second number: ");
            scanf("%d %d", &a, &b);
            multi = a * b;
            printf("The product of %d and %d is %d\n", a, b, multi);
            break;
        case '/': // Division
            printf("Enter the first and second number: ");
            scanf("%d %d", &a, &b);
            if(b == 0) {
                printf("Error: Cannot divide by zero!\n");
            } else {
                // 把其中一个数转成float,实现浮点除法
                div = (float)a / b;
                // 整数用%d,浮点数用%f,格式匹配
                printf("The division of %d by %d is %.2f\n", a, b, div);
            }
            break;
        default:
            printf("Error: Invalid operator, please retry!\n");
    }
    getch();
}

额外优化说明

  • 加了除数为0的判断:不管是除法还是取余,除数为0都会导致程序崩溃,这个判断能避免这种情况,还给用户清晰的错误提示。
  • 修复了运算符输入的换行符问题:在scanf(" %c", &character);里加个空格,会自动忽略之前输入的换行符,避免误读空字符触发default分支。
  • 统一了输出格式:严格按照变量类型使用%d(整数)和%f(浮点数),避免格式不匹配的异常。

内容的提问来源于stack exchange,提问作者GAMING INC

火山引擎 最新活动