用c语言编写一个计算机
时间: 2024-12-11 07:32:07 浏览: 10
在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) {
if (b != 0) {
return a / b;
} else {
printf("Error: Division by zero is not allowed.\n");
return 0; // 避免除以零的情况
}
}
int main() {
int num1, num2;
char operator;
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter an operator (+, -, *, /): ");
scanf(" %c", &operator);
switch (operator) {
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. Please use +, -, *, or /\n");
}
return 0;
}
```
阅读全文