输入一个形如A+B的四则运算式(加、减、乘、除),代表你向计算机出的题目。让计算机输出运算结果,请按样例格式输出。如果除数为0,输出非法操作信息:Illegal operation
时间: 2024-10-25 18:16:35 浏览: 79
假设我们有一个简单的函数`calculate_expression`来计算这样的四则运算表达式,我们可以编写以下代码来完成这个任务。这里是一个C++的例子:
```cpp
#include <iostream>
#include <stdexcept>
int calculate_expression(std::string expression) {
try {
size_t operator_pos = expression.find('+');
if (operator_pos == std::string::npos) { // no '+' found, assume it's a number
return std::stoi(expression); // convert to integer and return
}
std::string left operand = expression.substr(0, operator_pos);
std::string right_operand = expression.substr(operator_pos + 1);
char op = expression[op_pos]; // get the operator
if (op == '+') {
return std::stoi(left_operand) + std::stoi(right_operand);
} else if (op == '-') {
return std::stoi(left_operand) - std::stoi(right_operand);
} else if (op == '*') {
return std::stoi(left_operand) * std::stoi(right_operand);
} else if (op == '/') {
int right_value = std::stoi(right_operand);
if (right_value == 0) {
throw std::invalid_argument("Illegal operation: division by zero");
}
return std::stoi(left_operand) / right_value;
} else {
throw std::runtime_error("Unsupported operation: " + std::to_string(op));
}
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
return 0;
}
}
int main() {
std::string expression;
std::cout << "Enter an arithmetic expression (e.g., A+B): ";
std::getline(std::cin, expression);
int result = calculate_expression(expression);
if (result != 0) {
std::cout << "Result: " << result << std::endl;
}
return 0;
}
```
阅读全文