用c语言编写实现简单加减乘除整数的简单计算器
时间: 2024-10-16 11:06:27 浏览: 56
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;
char operation;
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
printf("Enter an operator (+, -, *, /): ");
scanf(" %c", &operation); // 用 " %c" 来消除多余的空白字符
switch(operation) {
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 operator!\n");
}
return 0;
}
```
阅读全文