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

如何根据用户输入选择算术运算?C代码编译报错求指导

问题:实现用户输入数字和运算符的算术运算时出现编译错误

我想要实现让用户输入两个数字和一个运算符,然后执行所选的算术运算,具体代码如下:

#include <stdio.h>
#include <stdlib.h>

int a;
int b;
int c;
int operation;

int main()
{
    printf("Enter First number :- ");
    scanf("%d" , &a);
    printf("Enter Second Number :- ");
    scanf("%d" , &b);
    printf("Enter Operator :- ");
    scanf("%d" , &c);

    #define DMAS c
    operation = (a DMAS b);
    printf("%d" , operation);
}

但在operation = (a DMAS b);这一行出现错误:

expected '(' before 'c'

作为编程新手,恳请指导我哪里出错了。


错误原因及解决方法

核心错误点

  1. 宏定义逻辑错误:C语言的宏是预编译阶段处理的,预编译时根本不知道变量c的运行时值。你把DMAS定义成c,预编译后代码会变成operation = (a c b);,这完全不符合C语言语法,编译器必然报错。
  2. 运算符输入类型错误:你用%d(整数格式)读取运算符,但运算符是字符(比如+、-),应该用%c读取,用整数类型存储运算符逻辑上也不匹配。

正确实现思路

不能用宏动态替换运算符,应该用条件判断(if-else或switch)根据用户输入的运算符执行对应运算。

修改后的代码

#include <stdio.h>

int main()
{
    int a, b;
    char op; // 用char类型存储运算符
    int result;

    printf("Enter First number :- ");
    scanf("%d", &a);
    printf("Enter Second Number :- ");
    scanf("%d", &b);
    // 前面加空格,避免读取上一次输入残留的换行符
    printf("Enter Operator (+, -, *, /) :- ");
    scanf(" %c", &op);

    // 用switch分支处理不同运算符
    switch(op) {
        case '+':
            result = a + b;
            break;
        case '-':
            result = a - b;
            break;
        case '*':
            result = a * b;
            break;
        case '/':
            // 增加除数为0的异常判断
            if(b != 0) {
                result = a / b;
            } else {
                printf("Error: 除数不能为0\n");
                return 1; // 异常退出程序
            }
            break;
        default:
            printf("Error: 无效的运算符\n");
            return 1;
    }

    printf("运算结果: %d\n", result);
    return 0;
}

额外说明

  • 把变量定义在main函数内,避免全局变量滥用,更符合C语言编码规范。
  • 加入了除数为0、无效运算符的异常处理,让程序更健壮。
  • 读取运算符时用" %c"(前面加空格),是为了跳过输入数字后留下的换行符,避免直接读取到空白字符导致逻辑错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 02:15:02