C语言编程实现简单的计算器功能,要求用户按如下格式从键盘输入算式: 操作数1 运算符op 操作数2 计算并输出表达式的值,其中算术运算符包括:加(+)、减(-)、乘(*)、除(/)。 **输入格式要求:"%d%c%d" 提示信息:"Please enter an expression:" **输出格式要求:"%d + %d = %d \n" "%d - %d = %d \n" "%d * %d = %d \n" "%d / %d = %d \n" "Division by zero!\n" "Invalid operator! \n" 程序运行示例1如下: Please enter an expression:22+12 22 + 12 = 34 程序运行示例2如下: Please enter an expression:22-12 22 - 12 = 10 程序运行示例3如下: Please enter an expression:22*12 22 * 12 = 264 程序运行示例4如下: Please enter an expression:22/12 22 / 12 = 1 程序运行示例5如下: Please enter an expression:22/0 Division by zero! 程序运行示例6如下: Please enter an expression:22\12 Invalid operator!
时间: 2024-03-05 15:49:01 浏览: 115
好的,以下是 C语言实现简单计算器的代码,注意输入格式和输出格式:
```c
#include <stdio.h>
int main() {
int num1, num2, result;
char operator;
printf("Please enter an expression:");
scanf("%d%c%d", &num1, &operator, &num2);
switch(operator) {
case '+':
result = num1 + num2;
printf("%d + %d = %d \n", num1, num2, result);
break;
case '-':
result = num1 - num2;
printf("%d - %d = %d \n", num1, num2, result);
break;
case '*':
result = num1 * num2;
printf("%d * %d = %d \n", num1, num2, result);
break;
case '/':
if(num2 == 0) {
printf("Division by zero!\n");
} else {
result = num1 / num2;
printf("%d / %d = %d \n", num1, num2, result);
}
break;
default:
printf("Invalid operator! \n");
}
return 0;
}
```
其中,switch语句根据输入的运算符进行不同的计算,并输出对应的结果或错误信息。需要注意的是,在除法中要判断被除数是否为0,避免出现除以0的错误。
阅读全文