如何用计算机做四则混合运算,C++实现计算器(四则混合运算)
时间: 2024-01-27 11:03:31 浏览: 40
实现计算器(四则混合运算)需要以下步骤:
1. 读入待计算的表达式
2. 将中缀表达式转换为后缀表达式
3. 用后缀表达式计算结果
以下是一个C++实现计算器(四则混合运算)的代码示例:
```c++
#include <iostream>
#include <stack>
#include <string>
#include <sstream>
#include <cmath>
using namespace std;
// 运算符优先级
int priority(char op) {
switch (op) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
default:
return 0;
}
}
// 中缀表达式转换为后缀表达式
string infix_to_postfix(string infix) {
stack<char> op_stack;
stringstream postfix_stream;
for (int i = 0; i < infix.length(); i++) {
char c = infix[i];
if (isdigit(c)) {
postfix_stream << c;
} else if (c == '(') {
op_stack.push(c);
} else if (c == ')') {
while (!op_stack.empty() && op_stack.top() != '(') {
postfix_stream << op_stack.top();
op_stack.pop();
}
if (!op_stack.empty() && op_stack.top() == '(') {
op_stack.pop();
}
} else {
while (!op_stack.empty() && priority(op_stack.top()) >= priority(c)) {
postfix_stream << op_stack.top();
op_stack.pop();
}
op_stack.push(c);
}
}
while (!op_stack.empty()) {
postfix_stream << op_stack.top();
op_stack.pop();
}
return postfix_stream.str();
}
// 计算后缀表达式
double evaluate_postfix(string postfix) {
stack<double> operand_stack;
for (int i = 0; i < postfix.length(); i++) {
char c = postfix[i];
if (isdigit(c)) {
operand_stack.push(c - '0');
} else {
double operand2 = operand_stack.top();
operand_stack.pop();
double operand1 = operand_stack.top();
operand_stack.pop();
switch (c) {
case '+':
operand_stack.push(operand1 + operand2);
break;
case '-':
operand_stack.push(operand1 - operand2);
break;
case '*':
operand_stack.push(operand1 * operand2);
break;
case '/':
operand_stack.push(operand1 / operand2);
break;
case '^':
operand_stack.push(pow(operand1, operand2));
break;
}
}
}
return operand_stack.top();
}
int main() {
string infix;
cout << "Enter an infix expression: ";
getline(cin, infix);
string postfix = infix_to_postfix(infix);
cout << "Postfix expression: " << postfix << endl;
double result = evaluate_postfix(postfix);
cout << "Result: " << result << endl;
return 0;
}
```
在上面的代码中,我们首先定义了一个 `priority` 函数来计算运算符的优先级。然后,我们定义了一个 `infix_to_postfix` 函数来将中缀表达式转换为后缀表达式,使用一个栈来存储运算符,使用一个字符串流来存储后缀表达式。
接下来,我们定义了一个 `evaluate_postfix` 函数来计算后缀表达式,使用一个栈来存储操作数,遇到运算符时弹出栈顶的两个操作数进行计算,将结果压入栈中。
最后,我们在 `main` 函数中读入中缀表达式,将其转换为后缀表达式并计算结果,输出结果。
需要注意的是,以上代码只能处理单个数字,如果需要处理多位数,需要进行修改。另外,以上代码也无法处理负数,需要进行特殊处理。