c++如何写一个计算器
时间: 2024-05-19 21:15:14 浏览: 14
可以使用 C 语言写一个简单的计算器。首先需要定义变量用于存储计算结果和用户输入的数值,然后使用 scanf 函数从用户输入中获取数值并进行运算,最后使用 printf 函数将计算结果输出。以下是一个简单的例子:
#include <stdio.h>
int main() {
int num1, num2, result;
char operator;
printf("请输入一个数值和一个操作符,以空格分隔:\n");
scanf("%d %c", &num1, &operator);
scanf("%d", &num2);
switch(operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
printf("无效的操作符,请重新输入!\n");
return 1;
}
printf("结果是:%d\n", result);
return 0;
}
相关问题
用C++写一个计算器程序
可以。下面是一个简单的计算器程序:
#include <stdio.h>
int main()
{
double num1, num2;
char operation;
printf("请输入要进行的运算:");
scanf("%lf %c %lf", &num1, &operation, &num2);
switch (operation)
{
case '+':
printf("%.1lf + %.1lf = %.1lf\n", num1, num2, num1 + num2);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf\n", num1, num2, num1 - num2);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf\n", num1, num2, num1 * num2);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf\n", num1, num2, num1 / num2);
break;
default:
printf("无效的运算符号\n");
}
return 0;
}
帮我用c++写一个计算器
好的,以下是一个简单的计算器示例代码:
```c
#include <stdio.h>
int main() {
char operator;
float num1, num2, result;
printf("请输入运算符 (+, -, *, /): ");
scanf("%c", &operator);
printf("请输入两个数字: ");
scanf("%f %f", &num1, &num2);
switch(operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
printf("错误的运算符\n");
return -1;
}
printf("%.2f %c %.2f = %.2f\n", num1, operator, num2, result);
return 0;
}
```
你可以根据需要进行修改和扩展。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.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)