我想使用QList将QLineEdit中的Qstring转换为double,以便它可以执行计算并在QMessagebox中显示结果。如果我能就如何做到这一点得到一些建议,那就太棒了。
#include <QtGui>
#include <QList>
#include <iostream>
int main (int argc, char* argv[])
{
QApplication app(argc, argv);
QTextStream cout(stdout);
bool ok;
double answer;
do
{
QString mark = QInputDialog::getText(NULL ,"MarkCalc","Enter Mark:", QLineEdit::Normal,"", &ok);
if (ok && !mark.isEmpty())
QList <QString> list;
double am = (mark * 0.20)+(mark * 0.50)+(mark * 0.30);
double ym = am * 0.20;
double em = 75 * 0.40;
double fm = em + ym;
if (em <= 40 && fm >= 50)
cout <<"pass";
else
cout << "fail";
QString response = QString("Your Final Mark: %1 \n\n%5").arg(ym).arg(em);
answer = QMessageBox::question(0, "Final Marks", response,QMessageBox::Yes | QMessageBox::No);
} while (answer == QMessageBox::Yes);
return 0;
}
答案 0 :(得分:0)
这是一个从OP获取代码并将QString拆分为QStringList的示例,然后使用foreach迭代列表,将列表中的每个QString转换为double,然后使用cout打印double:
#include <QtGui>
#include <QtCore>
#include <QtWidgets>
int main (int argc, char* argv[]) {
QApplication app(argc, argv);
QTextStream cout(stdout);
bool ok;
double answer;
do{
QString mark = QInputDialog::getText(NULL ,"MarkCalc","Enter Mark:", QLineEdit::Normal,"", &ok);
if (ok && !mark.isEmpty()) {
QStringList list = mark.split(",");
foreach(QString str, list) {
double d = str.toDouble();
cout << d << endl;
}
// double am = (mark * 0.20)+(mark * 0.50)+(mark * 0.30);
// double ym = am * 0.20;
// double em = 75 * 0.40;
// double fm = em + ym;
// if (em <= 40 && fm >= 50)
// cout <<"pass";
// else
// cout << "fail";
// QString response = QString("Your Final Mark: %1 \n\n%5").arg(ym).arg(em);
// answer = QMessageBox::question(0, "Final Marks", response,QMessageBox::Yes | QMessageBox::No);
}
} while (answer == QMessageBox::Yes);
return 0;
}
以下行使用逗号将QString拆分为QStringList。
QStringList list = mark.split(",");
之后我使用foreach迭代QStringList一个字符串,一次将每个字符串转换为double,并为每个double输出双行:
foreach(QString str, list) {
double d = str.toDouble();
cout << d << endl;
}