写简易计算器程序代码(C++)
时间: 2024-10-25 07:05:32 浏览: 8
编写一个简单的C++计算器程序,通常包括基本的加、减、乘、除功能,可以按照下面的步骤来实现:
```cpp
#include <iostream>
// 定义函数,分别代表加、减、乘、除操作
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
throw std::invalid_argument("Cannot divide by zero.");
}
int main() {
double num1, num2;
char operatorSymbol;
// 用户输入数字和运算符
std::cout << "Enter the first number: ";
std::cin >> num1;
std::cout << "Enter the second number: ";
std::cin >> num2;
std::cout << "Choose an operation (+, -, *, /): ";
std::cin >> operatorSymbol;
// 根据用户选择调用相应的函数
switch (operatorSymbol) {
case '+':
std::cout << "Result: " << add(num1, num2) << std::endl;
break;
case '-':
std::cout << "Result: " << subtract(num1, num2) << std::endl;
break;
case '*':
std::cout << "Result: " << multiply(num1, num2) << std::endl;
break;
case '/':
try {
std::cout << "Result: " << divide(num1, num2) << std::endl;
} catch (const std::invalid_argument& e) {
std::cerr << e.what() << std::endl;
}
break;
default:
std::cerr << "Invalid operator! Please choose from (+, -, *, /)." << std::endl;
break;
}
return 0;
}
```
阅读全文