用c语言写一个简单的计算器 包括加减乘除和阶乘等运算 并且计算器中有菜单选项
时间: 2024-09-10 11:12:07 浏览: 102
使用C语言实现简单计算器
5星 · 资源好评率100%
在C语言中编写一个简单的命令行计算器,包括基本的四则运算以及阶乘功能,我们可以设计一个结构化的菜单驱动程序。下面是一个基础的示例:
```c
#include <stdio.h>
#include <math.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 is not allowed.\n");
return 0;
}
double factorial(int n) {
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}
// 主菜单函数
void menu() {
int choice;
printf("\nCalculator Menu:\n");
printf("1. Addition\n");
printf("2. Subtraction\n");
printf("3. Multiplication\n");
printf("4. Division\n");
printf("5. Factorial\n");
printf("6. Exit\n");
scanf("%d", &choice);
switch (choice) {
case 1: // 加法
double num1, num2;
printf("Enter two numbers for addition: ");
scanf("%lf %lf", &num1, &num2);
printf("Result: %.2f\n", add(num1, num2));
break;
case 2: // 减法
scanf("%lf %lf", &num1, &num2);
printf("Result: %.2f\n", subtract(num1, num2));
break;
case 3: // 乘法
scanf("%lf %lf", &num1, &num2);
printf("Result: %.2f\n", multiply(num1, num2));
break;
case 4: // 除法
scanf("%lf %lf", &num1, &num2);
divide(num1, num2);
break;
case 5: // 阶乘
int fact_num;
printf("Enter an integer for factorial: ");
scanf("%d", &fact_num);
printf("Factorial: %d\n", factorial(fact_num));
break;
case 6: // 退出
printf("Exiting calculator...\n");
break;
default:
printf("Invalid choice. Please try again.\n");
break;
}
}
int main() {
while (true) {
menu();
}
return 0;
}
```
阅读全文