QT之简易计算器的实现

以前简单的学过QT,但这次重新学习感觉难度好大,可能是老了吧!哈哈

这是一个参考别人的程序再敲出来的,稍有改变。不会涉及侵权吧!
(如有,请联系删除吧!哈哈)

这是一个简易的计算器,可以实现基本的加减乘除,不过是手动输入式,不是按键的。
整体窗体只有两个控件,所以很清晰很简洁。

这是整体界面:

下面是代码:

mainwindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QMainWindow>
#include <QStack>
#include <windows.h>


namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

    QString AnlysisExpr(QString sInputExpr);
    QString GetWholeWord(const QString& sInput, const int nStartPos, int& nOutEndPos);

private:
    QString AddZeroBefore(QString str);
    void DeleteZero(QString& s);

private slots:
    void on_lineEdit_returnPressed();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

main.cpp:

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}
MainWindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDebug>
#include <QStack>
#include <QTextEdit>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);


    ui->lineEdit->setFont(QFont("Timers", 23, QFont::Bold));
    ui->textEdit_2->setFont(QFont("Timers", 14, QFont::Normal));

    setWindowFlags(Qt::WindowStaysOnTopHint);
}

MainWindow::~MainWindow()
{
    delete ui;
}

QString MainWindow::GetWholeWord(const QString& sInput, const int nStartPos, int& nOutEndPos)
{
    QString sWord;
    nOutEndPos = nStartPos;
    for(int i = nStartPos; i < sInput.length(); i++)
    {
        QChar ch = sInput.at(i);
        if((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch == '.'))
        {
            sWord += ch;
            nOutEndPos = i;
        }else{
            break;
        }
    }
    return sWord;
}

QString MainWindow::AnlysisExpr(QString sInputExpr)
{
    QStack<QString> stackMain;
    QStack<QString> stackOper;

    for(int i = 0; i < sInputExpr.length(); i++){
        QChar ch = sInputExpr[i];

        if(ch == ' '){
            continue;
        }else if(ch == '('){
            stackOper.push(QString(ch));
        }else if(ch == ')'){
            while(!stackOper.empty()){
                QString chPop = stackOper.pop();
                if(chPop != "("){
                    stackMain.push(chPop);
                }else{
                    break;
                }
            }
        }
        else if((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch == '.')){
          stackMain.push(GetWholeWord(sInputExpr, i, i));
        }else if(ch == '+' || ch == '-' || ch == '*' || ch == '/'){
            if(stackOper.empty()){
                stackOper.push(QString(ch));
            }else{
                QString chTemp = stackOper.top();
                while(((ch == '+' || ch == '-') && (chTemp == "*" || chTemp == "/"))
                      || ((ch == '+' || ch == '-') && (chTemp == "+" || chTemp == "-"))
                      || ((ch == '*' || ch == '/') && (chTemp == "*" || chTemp == "/"))){
                    stackMain.push(stackOper.pop());
                    if(stackOper.size() > 0){
                        chTemp = stackOper.top();
                    }else{
                        break;
                    }
                }
                stackOper.push(QString(ch));
            }
        }
    }

    while(!stackOper.empty()){
        QString chPop = stackOper.pop();
        stackMain.push(chPop);
    }

    QString sText;
    QStack<QString> stackCalc;
    while(!stackMain.empty()){
        QString chPop = stackMain.pop();
        stackCalc.push(chPop);
        sText.push_back(chPop);
    }

    QString sNewExpr;
    double dResultValue = sInputExpr.toDouble();
    {
        QString sOper;
        QStack<QString> stackTemp;
        QStack<double> stackTempValue;

        while(!stackCalc.empty()){
            QString sPop = stackCalc.pop();
            if(sPop.length() == 0){
                continue;
            }

            QChar ch = sPop.at(0);
            if(ch == '+' || ch == '-' || ch == '*' || ch == '/'){
                if(stackTemp.size() >= 2){
                    sOper = sPop;
                    QString s1 = stackTemp.pop();
                    QString s2 = stackTemp.pop();

                    if((sOper == "*" || sOper == "/") && (s2.contains('+') || s2.contains('-'))){
                        s2 = "(" + s2 + ")";
                    }

                    sNewExpr = QString("%1 %2 %3").arg(s2).arg(sOper).arg(s1);
                    stackTemp.push(sNewExpr);

                    double d1 = stackTempValue.pop();
                    double d2 = stackTempValue.pop();
                    switch(ch.cell()){
                        case '+':dResultValue = d2 + d1; break;
                        case '-':dResultValue = d2 - d1; break;
                        case '*':dResultValue = d2 * d1; break;
                        case '/':dResultValue = d2 / d1; break;
                    }
                    stackTempValue.push(dResultValue);
                }
            }else{
                stackTemp.push(sPop);
                stackTempValue.push(sPop.toDouble());
            }
        }
    }

    return QString::number(dResultValue, 'f', 10);
}

QString MainWindow::AddZeroBefore(QString str)
{
    QString s = str;
    if (s.isEmpty())
    {
        return s;
    }
    if (s[0] == '-')
    {
        s = QString("0") + s;
    }
    return s;
}

void MainWindow::DeleteZero(QString& s)
{
    int nPos = s.indexOf(".");
    if (nPos != -1)
    {
        int nNum = 0;
        for (int i=s.length()-1; i>=nPos; i--)
        {
            if (s[i] == '0' || s[i] == '.')
            {
                nNum++;
            }
            else
            {
                break;
            }
        }
        if (nNum>0)
        {
            s = s.left(s.length() - nNum);
        }
    }
}

void MainWindow::on_lineEdit_returnPressed()
{
    QString strInput = ui->lineEdit->text();
    if(strInput.isEmpty()){
        return ;
    }

    QString strNewInput = AddZeroBefore(strInput);
    QString strResult = AnlysisExpr(strNewInput);
    if(strResult.isEmpty()){
        return ;
    }

    DeleteZero(strResult);

    QString strRecord = strInput;
    if(strRecord.right(1) != "="){
        strRecord += "=";
    }
    strRecord += strResult;

    ui->lineEdit->clear();
    //ui->lineEdit->setText(strResult);
    ui->textEdit_2->setText(strRecord + "\n" + ui->textEdit_2->toPlainText());
}


 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值