简易计算器C语言代码
时间: 2024-06-13 08:01:56 浏览: 117
简易计算器C语言代码.doc
在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; // 或者抛出异常,这里简化为返回0
}
}
int main() {
int choice, num1, num2;
printf("Select operation:\n");
printf("1. Add\n");
printf("2. Subtract\n");
printf("3. Multiply\n");
printf("4. Divide\n");
scanf("%d", &choice);
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
switch (choice) {
case 1:
printf("Result: %d\n", add(num1, num2));
break;
case 2:
printf("Result: %d\n", subtract(num1, num2));
break;
case 3:
printf("Result: %d\n", multiply(num1, num2));
break;
case 4:
printf("Result: %d\n", divide(num1, num2));
break;
default:
printf("Invalid choice. Please try again.\n");
return 1;
}
return 0;
}
```
阅读全文