c语言,循环语句实现加减乘除的多步计算功能同时进行加减乘除,但不用考虑优先级的简单代码
时间: 2024-10-06 22:01:54 浏览: 74
在C语言中,你可以使用嵌套循环结构来实现加、减、乘、除的混合运算,这里假设用户输入四个数字和操作符,并按顺序执行这些操作。由于C语言没有直接支持四则运算的元运算符,我们需要手动判断每个操作符并执行相应的数学操作。下面是一个简单的示例:
```c
#include <stdio.h>
#include <math.h>
int main() {
int num1, num2;
char operator1, operator2;
printf("请输入两个数和两个操作符(如:5 + 3 - 4 * 2 / 2):");
scanf("%d %c %d %c", &num1, &operator1, &num2, &operator2);
// 将字符转换成对应的运算符
switch (operator1) {
case '+':
printf("First operation: %d + %d = ", num1, num2);
if (operator2 == '+' || operator2 == '-') {
num1 += num2;
} else {
printf("Invalid operator for the first operation.\n");
}
break;
case '-':
printf("First operation: %d - %d = ", num1, num2);
if (operator2 == '-' || operator2 == '+') {
num1 -= num2;
} else {
printf("Invalid operator for the first operation.\n");
}
break;
default:
printf("Invalid operator for the first operation.\n");
break;
}
switch (operator2) {
case '+':
printf("%d + %d\n", num1, num2);
break;
case '-':
printf("%d - %d\n", num1, num2);
break;
case '*':
printf("Multiplication: %d * %d = %d\n", num1, num2, num1*num2);
break;
case '/':
if (num2 != 0) {
printf("Division: %d / %d = %.2f\n", num1, num2, (float)num1/num2);
} else {
printf("Error: Division by zero is not allowed.\n");
}
break;
default:
printf("Invalid operator for the second operation.\n");
break;
}
return 0;
}
```
请注意,这个例子并没有处理所有可能的异常情况,例如除数为零。在实际应用中,你需要增加更多的错误检查和处理。
阅读全文