Добрый день! Разбирала пример калькулятора из книги Шлее. Возникает проблема, что при вычислении выражения, например, 2*5+4 при выполнении второй операции неверно записывается второй операнд (4 как 54). И аналогично при вычислении -5+4. В чем ошибка и как ее исправить? Большое спасибо за помощь! Код | #ifndef CALCULATOR_H #define CALCULATOR_H
#include <QWidget> #include <QStack> #include <QLCDNumber> #include <QPushButton>
class Calculator: public QWidget { Q_OBJECT private: QLCDNumber *m_plcd; QStack<QString> m_stk; QString m_strDisplay; public: explicit Calculator(QWidget *parent = 0); QPushButton* CreateButton(const QString &str); void Calculate(); ~Calculator() {} signals: public slots: void SlotButtonClicked(); }; #endif
|
Код | #include "Calculator.h" #include <QGridLayout> #include <QDebug> #include <string>
Calculator::Calculator(QWidget *parent): QWidget(parent) { m_plcd = new QLCDNumber(12); m_plcd->setSegmentStyle(QLCDNumber::Flat); m_plcd->setMinimumSize(150, 50); QChar aButtons[4][4] = {{'7', '8', '9', '/'}, {'4', '5', '6', '*'}, {'1', '2', '3', '-'}, {'0', '.', '=', '+'}}; QGridLayout* ptopLayout = new QGridLayout; ptopLayout->addWidget(m_plcd, 0, 0, 1, 4); ptopLayout->addWidget(CreateButton("C"), 1, 3); for (int i = 0;i < 4;i++) { for (int j = 0;j < 4;j++) { ptopLayout->addWidget(CreateButton(aButtons[i][j]), i + 2, j); } } setLayout(ptopLayout); }
QPushButton* Calculator::CreateButton(const QString &str) { QPushButton* pcmd = new QPushButton(str); pcmd->setMinimumSize(40, 40); connect(pcmd, SIGNAL(clicked()), SLOT(SlotButtonClicked())); return pcmd; }
void Calculator::Calculate() { double dOperand2 = m_stk.pop().toDouble(); QString strOperation = m_stk.pop(); double dOperand1 = m_stk.pop().toDouble(); double dResult = 0; if (strOperation == "+"){ dResult = dOperand1 + dOperand2; } if (strOperation == "-") { dResult = dOperand1 - dOperand2; } if (strOperation == "*") { dResult = dOperand1 * dOperand2; } if (strOperation == "/") { dResult = dOperand1 / dOperand2; } m_plcd->display(dResult); }
void Calculator::SlotButtonClicked() { QString str = ((QPushButton*)sender())->text(); if (str == "C") { m_stk.clear(); m_strDisplay = ""; m_plcd->display("0"); return; } if (str.contains(QRegExp("[0-9]"))) { m_strDisplay += str; m_plcd->display(m_strDisplay.toDouble()); } else { if (str == ".") { m_strDisplay += str; m_plcd->display(m_strDisplay); } else { if (m_stk.count() >= 2) { m_stk.push(QString().setNum(m_plcd->value())); Calculate(); m_stk.clear(); m_stk.push(QString().setNum(m_plcd->value())); if (str != "=") { m_stk.push(str); } } else { m_stk.push(QString().setNum(m_plcd->value())); m_stk.push(str); m_strDisplay = ""; m_plcd->display("0"); } } } }
|
Код | #include "Calculator.h" #include <QApplication>
int main(int argc, char *argv[]) { QApplication a(argc, argv); Calculator obj; obj.setWindowTitle("Calculator"); obj.resize(700, 500); obj.show(); return a.exec(); }
|
Это сообщение отредактировал(а) шарлотта - 3.11.2017, 22:09
|