用c语言设计一个简单的计算器,具有加、减、乘、除功能。第一行依次输入数值a,b; 第二行输入运算符,输入计算结果。(结果保留2位小数)
时间: 2024-05-11 08:18:32 浏览: 74
以下是一个简单的 C 语言计算器程序:
```c
#include <stdio.h>
int main() {
float a, b, result;
char operator;
printf("请输入两个数:\n");
scanf("%f %f", &a, &b);
printf("请输入运算符:\n");
scanf(" %c", &operator);
switch(operator) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
result = a / b;
break;
default:
printf("错误的运算符\n");
return 1;
}
printf("结果为:%.2f\n", result);
return 0;
}
```
程序首先提示用户输入两个数,然后提示用户输入运算符。运算符可以是加号、减号、乘号或除号。程序使用 switch 语句来根据运算符计算结果。最后,程序输出计算结果并退出。
注意,为了保留结果的小数点后两位,我们使用了 printf 函数的格式化输出功能,并在输出时使用了 %.2f 格式字符串。
相关问题
输入任意数值用c语言计算a+b a-b a*b a/b
在C语言中,你可以使用基本的算术运算符和条件判断语句来实现输入两个数值并计算它们的加、减、乘、除。下面是一个简单的示例程序:
```c
#include <stdio.h>
int main() {
float num1, num2, sum, difference, product, quotient;
// 输入两个数值
printf("请输入第一个数:");
scanf("%f", &num1);
printf("请输入第二个数:");
scanf("%f", &num2);
// 计算操作
sum = num1 + num2;
difference = num1 - num2;
product = num1 * num2;
// 对于除法,需要检查除数是否为零
if (num2 != 0) {
quotient = num1 / num2;
} else {
printf("错误:除数不能为零。\n");
return 1; // 如果遇到除零错误,程序可以返回1表示异常
}
// 输出结果
printf("a + b = %.2f\n", sum);
printf("a - b = %.2f\n", difference);
printf("a * b = %.2f\n", product);
printf("a / b = %.2f\n", quotient);
return 0;
}
```
这个程序会提示用户输入两个数字,并依次计算它们的和、差、积以及在非零的情况下商。注意在计算除法时对除数为零的情况进行了特判。
如何用C语言编写一个支持四则运算功能的计算器程序?
要在C语言中编写一个简单的四则运算计算器程序,你可以使用结构化编程和基本输入输出函数。以下是一个基础的示例,它通过循环读取用户输入并计算结果:
```c
#include <stdio.h>
// 函数声明用于加法、减法、乘法和除法
double add(double a, double b);
double subtract(double a, double b);
double multiply(double a, double b);
double divide(double a, double b);
int main() {
double num1, num2;
char operator;
printf("请输入第一个数字: ");
scanf("%lf", &num1);
printf("请输入运算符 (+,-,*,/): ");
scanf(" %c", &operator); // 注意这里添加空格避免把数字误认为运算符
switch (operator) {
case '+':
printf("请输入第二个数字: ");
scanf("%lf", &num2);
printf("%.2lf + %.2lf = %.2lf\n", num1, num2, add(num1, num2));
break;
case '-':
scanf("%lf", &num2);
printf("%.2lf - %.2lf = %.2lf\n", num1, num2, subtract(num1, num2));
break;
case '*':
scanf("%lf", &num2);
printf("%.2lf * %.2lf = %.2lf\n", num1, num2, multiply(num1, num2));
break;
case '/':
if (num2 != 0) { // 避免除数为零的情况
scanf("%lf", &num2);
printf("%.2lf / %.2lf = %.2lf\n", num1, num2, divide(num1, num2));
} else {
printf("错误: 除数不能为零!\n");
}
break;
default:
printf("错误: 无效的运算符.\n");
break;
}
return 0;
}
// 这些函数实现了具体的运算
double add(double a, double b) { return a + b; }
double subtract(double a, double b) { return a - b; }
double multiply(double a, double b) { return a * b; }
double divide(double a, double b) { return a / b; }
```
运行这个程序时,用户可以依次输入两个数值和运算符,然后会得到相应的计算结果。
阅读全文
相关推荐
















