6

这是我到目前为止所拥有的,但我无法弄清楚我的下一步。

当我将我的值除以 3 时,我得到整数,但我希望它以一位小数显示,但我不知道如何。

完成后,我想根据其值向上或向下舍入小数点。如果它是 3.5 或以上,它应该变成 4,如果它是 3.4 或以下,它应该是 3。

void MainWindow::on_pushButton_clicked(){

int paragraph = ui->lineEdit->text().toInt();
int section = ui->lineEdit_2->text().toInt();
int lines = ui->lineEdit_3->text().toInt();

int sum = (paragraph * (lines + 1) -(section * lines));

ui->label_4->setText(QString::number(sum/3));
}
4

2 回答 2

5

您正在除整数,因此得到整数。所以小数部分被截断。

int a = 11;
a = a / 3;        // a is 3 now

double b = 11;
b = b / 3;        // b is 3.6666... now

double c = a / 3; // c is 3 now
c = b / 3;        // c is 3.6666... now

运算符的返回类型,如,+或由其中的第一个对象确定。-*/

只需使用qRound(double(sum)/3.0)orqRound(double(sum)/3)来获得四舍五入的值。

如果要以 1 位小数显示结果,请使用QString::number(double(sum)/3.0, 'f', 1).

请在使用 C++ 之前学习 C 基础知识(阅读K&R的关键部分)。并在使用 Qt 之前学习 C++。

于 2013-11-14T18:49:21.457 回答
2

If you want to round up and down you can use the C++ math functions ceil and floor. ceil rounds up, and floor rounds down.

For the display you can specify QString::number(sum/3, 'f', 1) which specifies your number, the display format argument (there's an explanation of that here on the QString docs) and then finally sets 2 for the precision.

于 2013-11-14T18:42:15.547 回答