请用c++写一个简易计算器
时间: 2024-11-12 18:41:50 浏览: 4
当然可以,下面是一个简单的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;
}
int divide(int a, int b) {
if (b != 0)
return a / b;
else
throw "Error: Division by zero is not allowed!";
}
int main() {
cout << "Welcome to Simple Calculator!" << endl;
int num1, num2;
char operation;
cout << "Enter the first number: ";
cin >> num1;
cout << "Enter the operator (+, -, *, /): ";
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;
default:
cout << "Invalid operator! Please use +, -, *, or /." << endl;
break;
}
return 0;
}
```
在这个例子中,我们定义了四个函数分别对应加、减、乘、除操作,并在`main`函数中根据用户输入的运算符选择相应的函数进行计算。
阅读全文