c语言怎么实现一个计算器
时间: 2024-09-22 20:04:23 浏览: 37
在C语言中实现一个基本的计算器,可以采用函数或结构体结合控制结构来完成。这里给出一个简单的命令行界面计算器示例,它支持加减乘除运算:
```c
#include <stdio.h>
// 定义计算函数
int calculate(int num1, int num2, char operator) {
switch (operator) {
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
if (num2 != 0)
return num1 / num2;
else
printf("Error! Division by zero is not allowed.\n");
return 0; // 避免程序继续执行错误结果
default:
printf("Invalid operator.\n");
return 0;
}
}
int main() {
int num1, num2;
char operator;
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
printf("Enter an operator (+, -, *, /): ");
scanf(" %c", &operator);
int result = calculate(num1, num2, operator);
if (result) {
printf("The result is: %d\n", result);
}
return 0;
}
```
阅读全文