C语言编程实现一个简单的计算器。此计算器应具备基本计算功能:加法、减法、乘法、除法、阶乘等运算,请利用模块化程序设计的思想设计实现。提示:可利用有参有返回值函数实现计算器的各项功能。
时间: 2023-12-30 09:05:01 浏览: 82
下面是一个简单的 C 语言计算器的实现,包括加法、减法、乘法、除法和阶乘等运算:
```c
#include <stdio.h>
// 定义加法函数
double add(double a, double b) {
return a + b;
}
// 定义减法函数
double subtract(double a, double b) {
return a - b;
}
// 定义乘法函数
double multiply(double a, double b) {
return a * b;
}
// 定义除法函数
double divide(double a, double b) {
if (b != 0) {
return a / b;
} else {
printf("Error: Division by zero!\n");
return 0;
}
}
// 定义阶乘函数
double factorial(double n) {
double result = 1;
if (n < 0) {
printf("Error: Cannot compute factorial of a negative number!\n");
return 0;
} else {
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
}
int main() {
int choice;
double num1, num2, result;
printf("Welcome to the calculator program!\n");
printf("Please select an operation:\n");
printf("1. Addition\n");
printf("2. Subtraction\n");
printf("3. Multiplication\n");
printf("4. Division\n");
printf("5. Factorial\n");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter two numbers to add:\n");
scanf("%lf %lf", &num1, &num2);
result = add(num1, num2);
printf("Result: %lf\n", result);
break;
case 2:
printf("Enter two numbers to subtract:\n");
scanf("%lf %lf", &num1, &num2);
result = subtract(num1, num2);
printf("Result: %lf\n", result);
break;
case 3:
printf("Enter two numbers to multiply:\n");
scanf("%lf %lf", &num1, &num2);
result = multiply(num1, num2);
printf("Result: %lf\n", result);
break;
case 4:
printf("Enter two numbers to divide:\n");
scanf("%lf %lf", &num1, &num2);
result = divide(num1, num2);
printf("Result: %lf\n", result);
break;
case 5:
printf("Enter a number to compute its factorial:\n");
scanf("%lf", &num1);
result = factorial(num1);
printf("Result: %lf\n", result);
break;
default:
printf("Error: Invalid choice!\n");
break;
}
return 0;
}
```
在程序运行时,用户可以选择要进行的操作,然后输入相应的数值,计算器将输出计算结果。例如,如果用户选择加法操作并输入数值 2 和 3,则程序将输出 5。
阅读全文