我的第一个 Qt 程序有问题(应该是一个简单的计算器)。当我的计算器显示(lineEditDisplay)中已经有一个运算符并且我再次按下一个运算符时,我想计算每次。我的问题是他认出了一个“+”而不是一个“-”或“*”,我不知道为什么。
例如,如果我按 4,然后按 -,然后按 2,显示器显示我 4-2,但现在如果我按已发布的 + 按钮,我会显示 6+ 而不是 2+。所以它接缝它进入第一个 if 语句并计算 firstNumber+secondNumber。
这是添加按钮的单击槽:
void Calculator::on_pushButtonAddition_clicked()
{
QString inLineEditDisplay=ui->lineEditDisplay->text(); //Get whats in display
//Loop through display string
for(int i=0; i<inLineEditDisplay.length(); i++)
{
//Check if there is already a operator -> if yes then calculate first so
//we can add a new operator; first check for +
if(inLineEditDisplay[i]=='+')
{
//Get the two numbers; in front of and behind the operator
QString firstPart=inLineEditDisplay.left(i);
QString secondPart=inLineEditDisplay.right(inLineEditDisplay.length()-i);
//Change from QString to int, so we can calculate with
int firstPartAsInt=firstPart.toInt();
int secondPartAsInt=secondPart.toInt();
inLineEditDisplay=QString::number(firstPartAsInt+secondPartAsInt);
}
//Now check for -
if(inLineEditDisplay[i]=='-')
{
//Get the two numbers; in front of and behind the operator
QString firstPart=inLineEditDisplay.left(i);
QString secondPart=inLineEditDisplay.right(inLineEditDisplay.length()-i);
//Change from QString to int, so we can calculate with
int firstPartAsInt=firstPart.toInt();
int secondPartAsInt=secondPart.toInt();
inLineEditDisplay=QString::number(firstPartAsInt-secondPartAsInt);
}
//Now check for *
if(inLineEditDisplay[i]=='*')
{
//Get the two numbers; in front of and behind the operator
QString firstPart=inLineEditDisplay.left(i);
QString secondPart=inLineEditDisplay.right(inLineEditDisplay.length()-i);
//Change from QString to int, so we can calculate with
int firstPartAsInt=firstPart.toInt();
int secondPartAsInt=secondPart.toInt();
inLineEditDisplay=QString::number(firstPartAsInt*secondPartAsInt);
}
//Now check for /
if(inLineEditDisplay[i]=='/')
{
//Get the two numbers; in front of and behind the operator
QString firstPart=inLineEditDisplay.left(i);
QString secondPart=inLineEditDisplay.right(inLineEditDisplay.length()-i);
//Change from QString to int, so we can calculate with
int firstPartAsInt=firstPart.toInt();
int secondPartAsInt=secondPart.toInt();
inLineEditDisplay=QString::number(firstPartAsInt/secondPartAsInt);
}
}
inLineEditDisplay.append('+');
ui->lineEditDisplay->setText(inLineEditDisplay);
}
我也用
if(inLineEditDisplay[i]==QLatin1Char('+'))
但这并没有改变任何东西(看不到任何不同的行为)
@ https://stackoverflow.com/users/2422324/user2422324
计算器.cpp -> http://pastebin.com/1bsUgg3Y
计算器.h -> http://pastebin.com/F0kbkx4g
main.cpp -> http://pastebin.com/keCu6Gcr
计算器.ui -> http://pastebin.com/nTEauYAH