用c语言写一段代码,要求从标准输入中读入一个整数算术运算表达式,如5 - 1 * 2 * 3 + 12 / 2 / 2 = 。计算表达式结果,并输出。
时间: 2023-06-12 14:02:01 浏览: 180
好的,下面是您所需要的代码:
```c
#include <stdio.h>
int main() {
int result = 0; // 保存计算结果
int operand; // 操作数
char operator; // 操作符
int coefficient = 1; // 系数,用于处理乘除法
while (scanf("%d", &operand) != EOF) // 从标准输入中读取操作数
{
if (coefficient == 1) // 第一个操作数
result = operand;
else { // 非第一个操作数
switch (operator)
{
case '+':
result += operand * coefficient;
break;
case '-':
result -= operand * coefficient;
break;
case '*':
coefficient *= operand;
break;
case '/':
coefficient /= operand;
break;
default:
printf("无效的运算符!\n");
return 1;
}
}
scanf("%c", &operator); // 读取下一个字符
if (operator == '\n') // 输入结束
break;
// 处理空格
while (operator == ' ')
scanf("%c", &operator);
// 处理乘除法
if (operator == '*' || operator == '/')
{
scanf("%d", &operand);
if (operator == '*')
coefficient *= operand;
else if (operator == '/')
coefficient /= operand;
scanf("%c", &operator); // 读取下一个符号
}
else if (operator == '+' || operator == '-')
scanf("%c", &operator); // 读取下一个符号
else { // 无效的运算符
printf("无效的运算符!\n");
return 1;
}
}
printf("%d\n", result);
return 0;
}
```
注意:本代码只实现了加减乘除法,不支持括号、浮点数、负数等。如果您有更多需求,请自行扩展代码。