C语言版
时间: 2023-08-21 19:07:41 浏览: 52
好的,以下是一个基于C语言的迷你计算器的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
double num1, num2, result;
char operator;
printf("Enter first number: ");
scanf("%lf", &num1);
printf("Enter operator (+, -, *, /): ");
scanf(" %c", &operator);
printf("Enter second number: ");
scanf("%lf", &num2);
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 == 0) {
printf("Error: Division by zero");
exit(0);
} else {
result = num1 / num2;
}
break;
default:
printf("Error: Invalid operator");
exit(0);
}
printf("%.2lf %c %.2lf = %.2lf", num1, operator, num2, result);
return 0;
}
```
这个迷你计算器要求用户输入两个数和要进行的操作符,支持加减乘除四则运算。如果用户输入的操作符不是这四个中的任何一个,程序会输出错误消息并退出。如果用户输入的是除法运算符,并且第二个数是零,程序也会输出错误消息并退出。最终,程序会输出计算结果,保留两位小数。您可以根据需要进行修改和扩展。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)