加减乘除阶乘计算器c++
时间: 2024-10-09 16:06:03 浏览: 45
在C++中编写一个加减乘除以及阶乘的计算器,你可以创建一个简单的控制台应用程序,利用函数来分别处理这几种运算。下面是一个基础的示例:
```cpp
#include <iostream>
using namespace std;
// 计算整数相加
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;
}
// 计算整数相除(需要处理除数为0的情况)
double divide(int a, int b) {
if (b == 0) {
cout << "Error: Division by zero is not allowed." << endl;
return 0;
}
return static_cast<double>(a) / b;
}
// 计算阶乘
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int num1, num2;
char operation;
cout << "Enter the first number: ";
cin >> num1;
cout << "Enter the second number: ";
cin >> num2;
cout << "Choose an operation (+, -, *, /, ! for factorial): ";
cin >> operation;
switch (operation) {
case '+':
cout << "Result: " << add(num1, num2) << endl;
break;
case '-':
cout << "Result: " << subtract(num1, num2) << endl;
break;
case '*':
cout << "Result: " << multiply(num1, num2) << endl;
break;
case '/':
cout << "Result: " << divide(num1, num2) << endl;
break;
case '!':
cout << "Factorial of " << num1 << ": " << factorial(num1) << endl;
break;
default:
cout << "Invalid operation!" << endl;
}
return 0;
}
```
阅读全文