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));
}
Just use qRound(double(sum)/3.0) or qRound(double(sum)/3) to get rounded value. If you want to display result with 1 decimal, use QString::number(double(sum)/3.0, 'f', 1) .
We round 0.5 to the nearest even digit. Example: 7.5 rounds up to 8 (because 8 is an even number) but 6.5 rounds down to 6 (because 6 is an even number)
Rounding to the Nearest IntegerIf the digit in the tenths place is less than 5, then round down, which means the units digit remains the same; if the digit in the tenths place is 5 or greater, then round up, which means you should increase the unit digit by one.
However, INT actually is more sophisticated than that. INT rounds a number down using the Order rounding method. That is, it rounds a positive number down, towards zero, and a negative number down, away from zero. Therefore, it's easy to use INT to round a number up using the Math method.
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.
Just use qRound(double(sum)/3.0)
or qRound(double(sum)/3)
to get rounded value.
If you want to display result with 1 decimal, use 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With