编程实现简单的计算器功能,要求用户按如下格式从键盘输入算式: 操作数1 运算符op 操作数2 计算并输出表达式的值,其中算术运算符包括:加(+)、减(-)、乘(*)、除(/)。 要求使其能进行浮点数的算术运算,同时允许使用字符*、x与X作为乘号,并且允许输入的算术表达式中的操作数和运算符之间可以加入任意多个空格符。 **输入格式要求:"%f %c%f" 提示信息:"Please enter the expression:\n" **输出格式要求:"%f + %f = %f \n" "%f - %f = %f \n" "%f * %f = %f \n" "%f / %f = %f \n" "Division by zero!\n" "Invalid operator! \n" 程序运行示例1如下: Please enter the expression: 2.0 + 4.0 2.000000 + 4.000000 = 6.000000 程序运行示例2如下: Please enter the expression: 2.0 - 4.0 2.000000 - 4.000000 = -2.000000 程序运行示例3如下: Please enter the expression: 2.0 * 4.0 2.000000 * 4.000000 = 8.000000 程序运行示例4如下: Please enter the expression: 2.0 x 4.0 2.000000 * 4.000000 = 8.000000 程序运行示例5如下: Please enter the expression: 2.0 X 4.0 2.000000 * 4.000000 = 8.000000 程序运行示例6如下: Please enter the expression: 2.0 / 4.0 2.000000 / 4.000000 = 0.5000000 程序运行示例7如下: Please enter the expression: 2.0 / 0 Division by zero! 程序运行示例8如下: Please enter the expression: 2.0 \ 4.0 Invalid operator!
时间: 2023-11-27 08:50:23 浏览: 107
下面是代码实现:
```c
#include <stdio.h>
#include <ctype.h>
int main()
{
float num1, num2, result;
char op;
printf("Please enter the expression:\n");
if (scanf("%f %c%f", &num1, &op, &num2) != 3) {
printf("Invalid input!\n");
return 0;
}
if (op == '*' || op == 'x' || op == 'X') {
result = num1 * num2;
printf("%f * %f = %f \n", num1, num2, result);
} else if (op == '/') {
if (num2 == 0) {
printf("Division by zero!\n");
return 0;
}
result = num1 / num2;
printf("%f / %f = %f \n", num1, num2, result);
} else if (op == '+') {
result = num1 + num2;
printf("%f + %f = %f \n", num1, num2, result);
} else if (op == '-') {
result = num1 - num2;
printf("%f - %f = %f \n", num1, num2, result);
} else {
printf("Invalid operator! \n");
}
return 0;
}
```
阅读全文