#include <stdio.h>
#include <stdlib.h>
#define MAX_INPUT_SIZE 100 // 最大输入长度
int main()
{
char input[MAX_INPUT_SIZE]; // 储存用户输入
double result = 0.0; // 计算结果
char operator = '+'; // 默认运算符为'+'
printf("Simple Calculator\n");
printf("Supported operators: + - * / C A\n");
printf("Enter your calculation, then press '=' to get result.\n");
while (1) {
printf("Input: ");
fgets(input, MAX_INPUT_SIZE, stdin); // 从用户输入中读取一行
// 处理操作符
switch (input[0]) {
case '+':
case '-':
case '*':
case '/':
operator = input[0];
break;
case '=':
printf("Result: %.2lf\n", result); // 将结果输出至两位小数
break;
case 'C':
result = 0.0;
break;
case 'A':
result = 0.0;
operator = '+';
break;
default:
// 如果用户输入了数字,则进行运算
if ((input[0] >= '0' && input[0] <= '9') || input[0] == '.') // 数字和小数点
result = atof(input); // 将字符串转换为浮点数
else
printf("Invalid input.\n");
break;
}
// 根据运算符进行计算
switch (operator) {
case '+':
result += atof(input);
break;
case '-':
result -= atof(input);
break;
case '*':
result *= atof(input);
break;
case '/':
result /= atof(input);
break;
}
}
return 0;
}
示例测试:
```
Simple Calculator
Supported operators: + - * / C A
Enter your calculation, then press '=' to get result.
Input: 12.3+2-12+5=
Result: 7.30
```