编程实现简单的计算器功能,要求用户按如下格式从键盘输入算式: 操作数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-02-18 15:06:12 浏览: 69
图形用户编程.编写一个简单的计算器程序,要求有菜单,能进行简单的加减乘除运算。
5星 · 资源好评率100%
下面是 C 语言实现的代码:
```c
#include <stdio.h>
int main() {
int num1, num2, result;
char op;
printf("Please enter an expression:");
scanf("%d%c%d", &num1, &op, &num2);
switch(op) {
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");
break;
}
return 0;
}
```
阅读全文