devc++编写界面计算器有+-*/和括号
时间: 2023-10-17 22:11:47 浏览: 47
好的,我可以帮您实现这个计算器。您需要使用Dev-C++集成开发环境,以便在Windows上编写和运行C++代码。以下是一个基本的框架,您可以根据您的需求进行修改和扩展:
```c++
#include <iostream>
#include <stack>
#include <string>
using namespace std;
// 判断一个字符是否为操作符
bool isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
// 获取操作符的优先级
int getPriority(char op) {
if (op == '+' || op == '-') {
return 1;
} else if (op == '*' || op == '/') {
return 2;
} else {
return 0;
}
}
// 计算两个数的结果
double calculate(double a, double b, char op) {
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
default:
return 0;
}
}
// 计算中缀表达式的值
double evaluate(string expr) {
stack<double> operandStack; // 操作数栈
stack<char> operatorStack; // 操作符栈
for (int i = 0; i < expr.length(); i++) {
char c = expr[i];
if (isdigit(c)) { // 如果是数字,压入操作数栈
int j = i;
while (j < expr.length() && (isdigit(expr[j]) || expr[j] == '.')) {
j++;
}
operandStack.push(stod(expr.substr(i, j - i))); // 将字符串转换为浮点数
i = j - 1;
} else if (isOperator(c)) { // 如果是操作符
while (!operatorStack.empty() && isOperator(operatorStack.top()) &&
getPriority(operatorStack.top()) >= getPriority(c)) {
// 如果操作符栈顶的操作符优先级大于等于当前操作符,就弹出栈顶操作符并计算
double b = operandStack.top();
operandStack.pop();
double a = operandStack.top();
operandStack.pop();
char op = operatorStack.top();
operatorStack.pop();
operandStack.push(calculate(a, b, op));
}
operatorStack.push(c); // 将当前操作符压入操作符栈
} else if (c == '(') { // 如果是左括号,压入操作符栈
operatorStack.push(c);
} else if (c == ')') { // 如果是右括号,弹出操作符栈中的操作符并计算,直到遇到左括号
while (!operatorStack.empty() && operatorStack.top() != '(') {
double b = operandStack.top();
operandStack.pop();
double a = operandStack.top();
operandStack.pop();
char op = operatorStack.top();
operatorStack.pop();
operandStack.push(calculate(a, b, op));
}
operatorStack.pop(); // 弹出左括号
}
}
// 处理剩余的操作符
while (!operatorStack.empty()) {
double b = operandStack.top();
operandStack.pop();
double a = operandStack.top();
operandStack.pop();
char op = operatorStack.top();
operatorStack.pop();
operandStack.push(calculate(a, b, op));
}
return operandStack.top(); // 返回最终结果
}
int main() {
string expr;
cout << "请输入一个包含加减乘除和括号的中缀表达式:" << endl;
cin >> expr;
double result = evaluate(expr);
cout << "计算结果为:" << result << endl;
return 0;
}
```
这个程序可以接受用户输入一个包含加减乘除和括号的中缀表达式,并计算它的值。您可以根据需要进行扩展,例如添加GUI界面和输入框,以便用户可以通过单击按钮输入表达式。