command-line calculator in c
时间: 2024-12-20 10:31:26 浏览: 12
命令行计算器在C语言中通常是一个简单的程序,它允许用户通过终端输入数学运算指令并获取结果。这个程序会读取用户的输入,解析出操作符和操作数,然后计算并显示结果。以下是创建一个基础的命令行计算器的一个简单示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义基本的运算函数
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) {
if (b != 0)
return a / b;
else
return "Error! Division by zero is not allowed.";
}
int main() {
char op; // 运算符
double num1, num2;
printf("Enter first number: ");
scanf("%lf", &num1);
printf("Enter operator (+, -, *, /): ");
scanf(" %c ", &op); // 确保只接收字符,忽略空格
printf("Enter second number: ");
scanf("%lf", &num2);
switch(op) {
case '+':
printf("%.2lf + %.2lf = %.2lf\n", num1, num2, add(num1, num2));
break;
case '-':
printf("%.2lf - %.2lf = %.2lf\n", num1, num2, subtract(num1, num2));
break;
case '*':
printf("%.2lf * %.2lf = %.2lf\n", num1, num2, multiply(num1, num2));
break;
case '/':
printf("%.2lf / %.2lf = %.2lf\n", num1, num2, divide(num1, num2));
break;
default:
printf("Invalid operator!\n");
}
return 0;
}
```
阅读全文