帮我写一个计算器加减乘除的C语言代码
时间: 2024-10-24 20:14:17 浏览: 27
caculatorv1.1_简加减乘除计算器_
在C语言中编写一个简单的命令行计算器,可以处理基本的加减乘除操作,可以参考下面这个示例代码:
```c
#include <stdio.h>
// 定义计算函数
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
int multiply(int a, int b) {
return a * b;
}
int divide(int a, int b) {
// 防止除数为0的情况
if (b == 0) {
printf("Error: Division by zero is not allowed.\n");
return 0;
}
return a / b;
}
int main() {
int num1, num2, choice;
printf("Enter operation (+, -, *, /): ");
scanf("%d", &choice);
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
switch(choice) {
case '+':
printf("Result: %d\n", add(num1, num2));
break;
case '-':
printf("Result: %d\n", subtract(num1, num2));
break;
case '*':
printf("Result: %d\n", multiply(num1, num2));
break;
case '/':
printf("Result: %d\n", divide(num1, num2));
break;
default:
printf("Invalid operation! Please enter +, -, *, or /\n");
}
return 0;
}
```
阅读全文