C++ qt - 小数和四舍五入到整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19985397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
qt - decimals and round up to whole numbers
提问by Giefdonut
This is what I've got so far but I can't figure out my next steps.
这是我到目前为止所得到的,但我无法弄清楚我的下一步。
When I divide my value with 3 I get whole numbers but I want it to display with one decimal and I don't know how.
当我将我的值除以 3 时,我得到整数,但我希望它显示一位小数,但我不知道如何。
When that's done I want to round the decimal up or down depending on its value. If it's 3.5 or over it should become 4 and if it's 3.4 or under it should be 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));
}
回答by Obey-Kun
You are dividing integrers and therefore get integer. So fractional part is truncated.
您正在除以积分器,因此得到整数。所以小数部分被截断。
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
Return type of operators like +
, -
, *
or /
is determined by first object in there.
+
, -
, *
or等运算符的返回类型/
由其中的第一个对象确定。
Just use qRound(double(sum)/3.0)
or qRound(double(sum)/3)
to get rounded value.
只需使用qRound(double(sum)/3.0)
或qRound(double(sum)/3)
获得四舍五入的值。
If you want to display result with 1 decimal, use QString::number(double(sum)/3.0, 'f', 1)
.
如果要以 1 位小数显示结果,请使用QString::number(double(sum)/3.0, 'f', 1)
.
Please study C basics (read critical parts of K&R) before using C++. And study C++ before using Qt.
请在使用 C++ 之前学习 C 基础知识(阅读K&R 的关键部分)。并在使用 Qt 之前学习 C++。
回答by Nicholas Smith
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.
如果你想向上和向下取整,你可以使用 C++ 数学函数ceil
和floor
. ceil
向上floor
舍入,向下舍入。
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.
对于显示,您可以指定QString::number(sum/3, 'f', 1)
哪个指定您的数字,显示格式参数(在 QString 文档中对此有解释),然后最后为精度设置 2。