You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言计算器程序无法正确执行运算的问题求助

C语言计算器程序无法正确执行运算的问题求助

问题描述

我是个纯纯的编程新手,肯定有什么很基础的地方被我漏掉了,但不知道为啥这段代码总是输出第一个变量的值,而不是加减乘除的运算结果,麻烦各位大佬帮忙看看问题出在哪?

#include <stdio.h>
int main(){
    int numone=0, numtwo=0;
    char sign;
    printf("Please enter the first number: ");
    scanf("%d", &numone);
    printf("Please enter the second number: ");
    scanf("%d", &numtwo);
    printf("Please enter the operation: ");
    scanf("%s", &sign);
    switch (sign) {
        case '+': printf("The result is: %d", numone + numtwo); break;
        case '-': printf("The result is: %d", numone - numtwo); break;
        case '*': printf("The result is: %d", numone * numtwo); break;
        case '/': printf("The result is: %d", numone / numtwo); break;
        default: printf("Error! operator is not correct");
    }
    return 0;
}

问题分析与解决方案

你遇到的问题根源出在**scanf("%s", &sign);**这一行上:

  • %s是用来读取字符串的格式符,它会把输入的字符加上一个终止符\0一起存入内存。但你的sign是单个char类型变量,内存空间只有1字节,写入字符串时会越界覆盖掉相邻的内存区域——刚好numtwo的内存位置就在sign旁边,被覆盖后变成了0,所以不管你做什么运算,结果都会等于numone + 0/numone - 0,看起来就像是只输出了第一个变量。

解决方法很简单,把读取运算符的代码改成用单个字符的格式符%c,同时要注意处理前面输入数字后留下的换行符:

// 用空格跳过前面输入残留的换行符和空白字符
scanf(" %c", &sign);

另外还有几个小建议可以优化你的代码:

  • 做除法的时候最好判断一下numtwo是否为0,避免除以0的运行时错误;
  • 输出结果后可以加个换行符\n,让终端输出更美观。

修改后的完整代码示例:

#include <stdio.h>
int main(){
    int numone=0, numtwo=0;
    char sign;
    printf("Please enter the first number: ");
    scanf("%d", &numone);
    printf("Please enter the second number: ");
    scanf("%d", &numtwo);
    printf("Please enter the operation: ");
    // 跳过空白字符后读取单个运算符
    scanf(" %c", &sign);
    switch (sign) {
        case '+': 
            printf("The result is: %d\n", numone + numtwo); 
            break;
        case '-': 
            printf("The result is: %d\n", numone - numtwo); 
            break;
        case '*': 
            printf("The result is: %d\n", numone * numtwo); 
            break;
        case '/': 
            if(numtwo == 0){
                printf("Error! Cannot divide by zero\n");
            } else {
                printf("The result is: %d\n", numone / numtwo); 
            }
            break;
        default: 
            printf("Error! operator is not correct\n");
    }
    return 0;
}

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.09 03:00:28