Hi, I am polishing up on my C++ and getting frustrated with this problem, would appreciate some help.
I need to enter a value eg 2.13 and return a rounded value with multiples of 0.5. So the answer should be 2.15 in this case.
Some of the rounding methods online are very confusing to me as i am just a beginner. Thanks in advance!
Since this is not a typical rounding issue you cannot use the rounding function.
You can use integer division:
1 2 3 4 5
|
int multiples_of_5 = int(x * 100) / 5; // Note: int(x * 100) simply truncates ther third digit
if((x * 100) > (multiples_of_5 * 5))
return ((multiples_of_5 + 1) * 5);
else
return (multiples_of_5 * 5);
|
Note: This is for
positive numbers only!
Last edited on
Took me some time to play around with the codes and finally got it to work.
Thanks guys!