支持常用算术功能,支持表达式。
1.关联信号与槽
.h
private slots:
void mySlot(QString);
signals:
void mySignal1(QString);
.cpp
connect(this,SIGNAL(mySignal1(QString)),this,SLOT(mySlot(QString)));
2.按键的槽函数:显示输入信息和计算最终结果
将输入信息显示在输入文本框内,待"="按下后,计算出表达式的值。
void MainWindow::mySlot(QString str)
{
Solution result;
if(str == "C"){
string.clear();
ui->lineEdit_2->setText(string);
ui->lineEdit->setText(string);
}
else if(str == "="){
double num = result.solve(string);//计算出最终结果,
QString str1 = QString::number(num);
ui->lineEdit->setText(str1);
}
else if(str == "del"){
string = string.left(string.length()-1);
ui->lineEdit_2->setText(string);
}
else if(str == "CE"){
int i= string.length();
while(--i)
{
if(string[i]=='*'||string[i]=='+'||string[i]=='-'||string[i]=='/')
break;
}
string = string.left(i+1);
ui->lineEdit_2->setText(string);
}
else{
string = string + str;
ui->lineEdit_2->setText(string);
}
}
3.表达式求值函数(符合四则运算法则)
double Solution::solve(QString s)
{
QStack <double> val;
QStack <char> ops;
for(int i=0; i<=s.length();)
{
if(s[i]>='0'&&s[i]<='9')
val.push(getNum(s, i));
else if(ops.empty())
ops.push(s[i++].toLatin1());
else if(s[i]=='*')
{
double t1=val.top(),t2=getNum(s, ++i);
val.pop();
val.push(t1*t2);
}
else if(s[i] == '/')
{
double t1=val.top(),t2=getNum(s, ++i);
val.pop();
val.push(t1/t2);
}
else
{
double t2=val.top();
val.pop();
double t1=val.top();
val.pop();
if(ops.top()=='+')
val.push(t1+t2);
else if(ops.top()=='-')
val.push(t1-t2);
else if(ops.top()=='*')
val.push(t1*t2);
else if(ops.top()=='/')
val.push(t1/t2);
ops.pop();
if(i==s.length())
break;
}
}
return val.top();
}
double Solution::getNum(QString s, int &i)
{
double integer=0.0;
while(s[i]<='9'&&s[i]>='0')
{
integer=integer*10+s[i++].toLatin1()-'0';
}
double decimal = 0.0;
if(s[i] == '.')
{
i++;
int j = 0;
while(s[i]<='9'&&s[i]>='0')
{
decimal=decimal*10+s[i++].toLatin1()-'0';
j++;
}
while(j--)
{
decimal/=10;
}
}
return integer + decimal;
}