- #include <stdio.h>
- #include <stdlib.h>
- #include <ctype.h>
- int main() {
- char op;
- double num1, num2, result;
- printf("命令行计算器\n");
- printf("请输入表达式 (例如: 1 + 2): ");
- // 读取第一个数字
- scanf("%lf", &num1);
- // 读取运算符
- while ((op = getchar()) != '+' && op != '-' && op != '*' && op != '/' && !isspace(op));
- if (!isspace(op)) {
- ungetc(op, stdin); // 如果不是运算符,则放回输入流
- scanf("%*c"); // 跳过非运算符字符
- printf("无效的运算符,请重新输入表达式: ");
- return 1;
- }
- // 读取第二个数字
- scanf("%lf", &num2);
- // 执行计算
- switch (op) {
- case '+':
- result = num1 + num2;
- break;
- case '-':
- result = num1 - num2;
- break;
- case '*':
- result = num1 * num2;
- break;
- case '/':
- if (num2 == 0) {
- printf("错误: 除数不能为0\n");
- return 1;
- }
- result = num1 / num2;
- break;
- default:
- printf("无效的运算符\n");
- return 1;
- }
- // 输出结果
- printf("%.2lf %c %.2lf = %.2lf\n", num1, op, num2, result);
- return 0;
- }
- 这个计算器程序会提示用户输入一个表达式,然后读取两个数字和一个运算符。根据运算符执行相应的计算,并输出结果。如果用户输入了无效的运算符或尝试除以零,程序会输出错误信息。