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

C语言简易计算器输出异常排查请求:乘法得0、加减仅显示首数

C语言简易计算器输出异常问题排查

你的代码存在三个关键错误,直接导致了输出不符合预期的问题:

1. 运算符读取的格式符错误

scanf("%s", &op); 中,%s 用于读取字符串,但 op 是单个 char 类型变量。使用 %s 会将输入的运算符(如 +)和字符串终止符 \0 写入内存,而 op 仅占1字节,后续的 \0 会覆盖相邻的 num2 变量内存,导致 num2 被重置为0。这就是乘法结果为0(num1 * 0)、加减仅显示第一个数字(num1 + 0/num1 - 0)的核心原因。

修正方案:使用 %c 格式符读取单个字符,同时在格式符前加空格跳过输入缓冲区中残留的换行符:

scanf(" %c", &op);

2. 加法分支的局部变量冗余问题

在加法分支中,你重新定义了局部变量 int ans,虽然此处printf直接使用该局部变量不会导致结果错误,但属于冗余代码,建议删除局部定义,直接使用main函数中声明的ans:

ans = add(num1, num2);
printf("Answer: %d", ans);

3. 减法分支的拼写错误

减法分支中的printf语句存在拼写错误:printf("Aswer: %d", ans);,其中 Aswer 应为 Answer,修正后:

printf("Answer: %d", ans);

修正后的完整代码

#include <stdio.h>
#include <math.h>

//Creating a simple calculator in c

//add func
int add(int n1, int n2)
{
    int result = n1 + n2;
    return(result);
}

//subtract func
int subtract(int n1, int n2)
{
    int result = n1 - n2;
    return(result);
}

//divide func
int divide(int n1, int n2)
{
    int result = n1 / n2;
    return(result);
}

//multiply func
int multiply(int n1, int n2)
{
    int result = n1 * n2;
    return(result);
}

int main()
{
    int num1, num2, ans;
    char op;//op means operator

    //use input
    printf("Enter first number: ");
    scanf("%d", &num1); //takes first number
    printf("\nEnter second number: ");
    scanf("%d", &num2); //takes second number
    printf("\nEnter operation: ");
    scanf(" %c", &op); //takes an operator character like '+', '-', '/', '*'

    //checks which operator has been inputted 
    if (op =='+')
    {
        ans = add(num1, num2);
        printf("Answer: %d", ans);
    }
    else if (op=='-')
    {
        ans = num1-num2;
        printf("Answer: %d", ans);
    }
    else if (op=='/')
    {
        ans = divide(num1, num2);
        printf("Answer: %d",ans);
    }
    else if (op == '*')
    {
        ans = multiply(num1, num2);
        printf("Answer: %d",ans);
    }
    else //exits with error if input instead of + - / *
    {
        printf("Invalid operator!");
    }
    
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 22:01:37