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.
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.
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));
}
Run Code Online (Sandbox Code Playgroud)
您正在划分积分器,因此得到整数。所以小数部分被截断。
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
Run Code Online (Sandbox Code Playgroud)
+, -, *or等运算符的返回类型/由其中的第一个对象确定。
只需使用qRound(double(sum)/3.0)或qRound(double(sum)/3)获得四舍五入的值。
如果要以 1 位小数显示结果,请使用QString::number(double(sum)/3.0, 'f', 1).
请在使用 C++ 之前学习 C 基础知识(阅读K&R 的关键部分)。并在使用 Qt 之前学习 C++。
如果您想向上和向下舍入,可以使用 C++ 数学函数ceil和floor。ceil向上舍入和floor向下舍入。
对于显示,您可以指定指定您的数字、显示格式参数( QString 文档中QString::number(sum/3, 'f', 1)对此有解释),然后最后将精度设置为 2。