用c语言编程实现一个简单的计算器,具备加法,减法,乘法,除法,阶乘等运算
时间: 2023-10-09 09:08:53 浏览: 118
好的,以下是 C 语言的实现示例:
```c
#include <stdio.h>
int add(int x, int y) {
return x + y;
}
int subtract(int x, int y) {
return x - y;
}
int multiply(int x, int y) {
return x * y;
}
float divide(int x, int y) {
if (y == 0) {
printf("Error: Division by zero is not allowed\n");
return 0;
} else {
return (float)x / y;
}
}
int factorial(int x) {
if (x < 0) {
printf("Error: Factorial of a negative number is not defined\n");
return 0;
} else if (x == 0) {
return 1;
} else {
return x * factorial(x-1);
}
}
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");
printf("5.Factorial\n");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter first number: ");
scanf("%d", &num1);
printf("Enter second number: ");
scanf("%d", &num2);
printf("%d + %d = %d\n", num1, num2, add(num1, num2));
break;
case 2:
printf("Enter first number: ");
scanf("%d", &num1);
printf("Enter second number: ");
scanf("%d", &num2);
printf("%d - %d = %d\n", num1, num2, subtract(num1, num2));
break;
case 3:
printf("Enter first number: ");
scanf("%d", &num1);
printf("Enter second number: ");
scanf("%d", &num2);
printf("%d * %d = %d\n", num1, num2, multiply(num1, num2));
break;
case 4:
printf("Enter first number: ");
scanf("%d", &num1);
printf("Enter second number: ");
scanf("%d", &num2);
printf("%d / %d = %.2f\n", num1, num2, divide(num1, num2));
break;
case 5:
printf("Enter a non-negative integer: ");
scanf("%d", &num1);
printf("%d! = %d\n", num1, factorial(num1));
break;
default:
printf("Invalid Input\n");
}
return 0;
}
```
这个程序会根据用户的选择进行不同的计算操作,使用了函数来实现每种运算,同时还有对除零和负数阶乘的错误处理。注意输出浮点数除法结果时使用了 `%.2f` 格式化字符串控制输出精度。
阅读全文