如何用计算机做四则混合运算,C++实现计算器(四则混合运算)
时间: 2024-01-27 07:03:31 浏览: 21
为了实现计算器,我们需要以下步骤:
1. 读入用户输入的表达式
2. 将表达式转换为后缀表达式
3. 计算后缀表达式的值
4. 输出结果
具体步骤如下:
1. 读入用户输入的表达式
我们可以使用 `cin` 函数读入用户输入的表达式,例如:
```c++
string expr;
cout << "请输入表达式:";
cin >> expr;
```
2. 将表达式转换为后缀表达式
将中缀表达式转换为后缀表达式的算法有很多种,其中比较常用的是使用栈来实现。具体步骤如下:
- 从左到右遍历中缀表达式的每个元素
- 如果当前元素是数字,直接输出
- 如果当前元素是左括号,将其入栈
- 如果当前元素是右括号,将栈顶元素依次出栈并输出,直到遇到左括号为止
- 如果当前元素是运算符,将其与栈顶元素比较:
- 如果栈顶元素是左括号或栈为空,将运算符入栈
- 如果栈顶元素的优先级比运算符低或相等,将栈顶元素出栈并输出,直到栈为空或栈顶元素的优先级比运算符高
- 将运算符入栈
例如,对于表达式 `3+4*5/(2-1)`,其对应的后缀表达式为 `345*21-/+`。
```c++
string infixToPostfix(string expr) {
string postfix;
stack<char> opStack;
for (int i = 0; i < expr.length(); i++) {
char ch = expr[i];
if (isdigit(ch)) {
postfix += ch;
} else if (ch == '(') {
opStack.push(ch);
} else if (ch == ')') {
while (!opStack.empty() && opStack.top() != '(') {
postfix += opStack.top();
opStack.pop();
}
opStack.pop();
} else if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {
while (!opStack.empty() && opStack.top() != '(' && getPriority(opStack.top()) >= getPriority(ch)) {
postfix += opStack.top();
opStack.pop();
}
opStack.push(ch);
}
}
while (!opStack.empty()) {
postfix += opStack.top();
opStack.pop();
}
return postfix;
}
```
其中,`getPriority` 函数用于获取运算符的优先级,实现如下:
```c++
int getPriority(char op) {
if (op == '+' || op == '-') {
return 1;
} else if (op == '*' || op == '/') {
return 2;
} else {
return 0;
}
}
```
3. 计算后缀表达式的值
计算后缀表达式的值也可以使用栈来实现。具体步骤如下:
- 从左到右遍历后缀表达式的每个元素
- 如果当前元素是数字,将其入栈
- 如果当前元素是运算符,将栈顶的两个元素出栈并进行运算,将结果入栈
- 最后栈中的元素即为表达式的值
例如,对于后缀表达式 `345*21-/+`,其值为 `17`。
```c++
int evalPostfix(string expr) {
stack<int> valStack;
for (int i = 0; i < expr.length(); i++) {
char ch = expr[i];
if (isdigit(ch)) {
valStack.push(ch - '0');
} else if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {
int val2 = valStack.top();
valStack.pop();
int val1 = valStack.top();
valStack.pop();
int result;
switch (ch) {
case '+': result = val1 + val2; break;
case '-': result = val1 - val2; break;
case '*': result = val1 * val2; break;
case '/': result = val1 / val2; break;
}
valStack.push(result);
}
}
return valStack.top();
}
```
4. 输出结果
最后,我们可以使用 `cout` 函数输出表达式的计算结果,例如:
```c++
string expr;
cout << "请输入表达式:";
cin >> expr;
string postfix = infixToPostfix(expr);
int result = evalPostfix(postfix);
cout << "计算结果为:" << result << endl;
```
完整的代码如下: