表达式求值数据结构easyX 输入框
时间: 2023-06-30 09:12:11 浏览: 191
以下是一个使用 easyX 图形界面实现表达式求值的例子。用户可以在输入框中输入表达式,点击“计算”按钮后,程序将计算出表达式的结果,并在输出框中显示。
```c++
#include <graphics.h>
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int priority(char op) {
switch (op) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '(':
case ')':
return 0;
default:
return -1;
}
}
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> nums;
stack<char> ops;
for (int i = 0; i < expr.length(); i++) {
char ch = expr[i];
if (isdigit(ch)) {
double num = 0;
while (i < expr.length() && isdigit(expr[i])) {
num = num * 10 + (expr[i] - '0');
i++;
}
i--;
nums.push(num);
}
else if (ch == '(') {
ops.push(ch);
}
else if (ch == ')') {
while (!ops.empty() && ops.top() != '(') {
char op = ops.top();
ops.pop();
double b = nums.top();
nums.pop();
double a = nums.top();
nums.pop();
nums.push(calculate(a, b, op));
}
ops.pop();
}
else {
while (!ops.empty() && priority(ops.top()) >= priority(ch)) {
char op = ops.top();
ops.pop();
double b = nums.top();
nums.pop();
double a = nums.top();
nums.pop();
nums.push(calculate(a, b, op));
}
ops.push(ch);
}
}
while (!ops.empty()) {
char op = ops.top();
ops.pop();
double b = nums.top();
nums.pop();
double a = nums.top();
nums.pop();
nums.push(calculate(a, b, op));
}
return nums.top();
}
int main() {
initgraph(400, 300);
settextstyle(20, 0, _T("Arial"));
setbkcolor(WHITE);
// 输入框
RECT rect = { 50, 50, 350, 100 };
drawtext(_T("请输入表达式:"), &rect, DT_LEFT | DT_VCENTER | DT_SINGLELINE);
rect.top += 50;
rect.bottom += 50;
rect.right -= 50;
setfillcolor(LIGHTGRAY);
fillrectangle(&rect);
setbkmode(TRANSPARENT);
settextcolor(BLACK);
settextstyle(16, 0, _T("Arial"));
string expr;
char ch;
while (ch = _getche()) {
if (ch == 13) { // 回车键
break;
}
else if (ch == 8) { // 退格键
if (!expr.empty()) {
expr.pop_back();
rect.right -= 10;
fillrectangle(&rect);
}
}
else if (ch >= 32 && ch <= 126) { // 可打印字符
expr.push_back(ch);
drawtext(expr.c_str(), &rect, DT_LEFT | DT_VCENTER | DT_SINGLELINE);
rect.right += 10;
}
}
// 计算按钮
rect.top += 50;
rect.bottom += 50;
rect.left += 100;
rect.right -= 100;
setfillcolor(LIGHTGRAY);
fillrectangle(&rect);
drawtext(_T("计算"), &rect, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
// 输出框
rect.top += 50;
rect.bottom += 50;
rect.right += 50;
rect.left -= 50;
setfillcolor(LIGHTGRAY);
fillrectangle(&rect);
settextstyle(20, 0, _T("Arial"));
double result = evaluate(expr);
TCHAR buf[100];
_stprintf_s(buf, _T("结果为:%.2f"), result);
drawtext(buf, &rect, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
getch();
closegraph();
return 0;
}
```
运行程序后,用户可以在输入框中输入表达式,如 `2*(3+4)/5-6`,然后点击“计算”按钮,程序将计算出表达式的结果,并在输出框中显示。
阅读全文