用c语言编程一个简单计算器,可以有多个数加分,减法,乘法,除法,阶乘等运算
时间: 2023-10-10 15:15:43 浏览: 107
使用C语言实现简单计算器
5星 · 资源好评率100%
好的,以下是 C 语言的实现示例:
```c
#include <stdio.h>
int add(int *nums, int n) {
int sum = 0;
for (int i = 0; i < n; i++) {
sum += nums[i];
}
return sum;
}
int subtract(int *nums, int n) {
int result = nums[0];
for (int i = 1; i < n; i++) {
result -= nums[i];
}
return result;
}
int multiply(int *nums, int n) {
int result = 1;
for (int i = 0; i < n; i++) {
result *= nums[i];
}
return result;
}
float divide(int *nums, int n) {
int divisor = nums[0];
for (int i = 1; i < n; i++) {
if (nums[i] == 0) {
printf("Error: Division by zero is not allowed\n");
return 0;
} else {
divisor /= nums[i];
}
}
return (float)divisor;
}
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, n;
int nums[10];
while (1) {
printf("\nSelect operation.\n");
printf("1.Add\n");
printf("2.Subtract\n");
printf("3.Multiply\n");
printf("4.Divide\n");
printf("5.Factorial\n");
printf("6.Quit\n");
scanf("%d", &choice);
if (choice == 6) {
break;
}
printf("Enter number of operands: ");
scanf("%d", &n);
if (n > 10) {
printf("Error: Maximum number of operands is 10\n");
continue;
}
printf("Enter %d operands: ", n);
for (int i = 0; i < n; i++) {
scanf("%d", &nums[i]);
}
switch (choice) {
case 1:
printf("Result: %d\n", add(nums, n));
break;
case 2:
printf("Result: %d\n", subtract(nums, n));
break;
case 3:
printf("Result: %d\n", multiply(nums, n));
break;
case 4:
printf("Result: %.2f\n", divide(nums, n));
break;
case 5:
printf("Result: %d\n", factorial(nums[0]));
break;
default:
printf("Invalid Input\n");
}
}
printf("Goodbye!\n");
return 0;
}
```
这个程序会循环显示菜单,用户可以输入多个操作数,根据用户的选择进行不同的计算操作,使用了函数来实现每种运算,同时还有对除零和负数阶乘的错误处理。注意输出浮点数除法结果时使用了 `%.2f` 格式化字符串控制输出精度。用户可以选择退出程序。
阅读全文