+ 5
Code coach problems involving rounding.
Many of the code coach problems involves "rounding to nearest integer " where you round a float or double into an int. I implemented my own algorithm for solving and it worked. But i was hoping if there is a much more efficient way. Please help. Edit: sorry for not posting my code earlier. https://code.sololearn.com/ccIPJii3Lh7D/?ref=app
10 Antworten
+ 2
Just like HonFu and KnuckleBars said, you can use round() function
To know more about it visit this link 👇
https://www.programiz.com/cpp-programming/library-function/cmath/round
OR
if you want to create your own function only then try this one liner👇
int roundNo(float num)
{
return num < 0 ? num - 0.5 : num + 0.5;
}
+ 4
I've shared it now. I apologise for not including it in the original question.
+ 3
In order to see if there's a better way than yours, we'd first have to see yours!
So... care to share? (Not the complete solution please!)
Some problems want round, others want ceil, and countless questions were asked because people somehow ignored the difference between 'round' and 'round up'.
+ 3
Thank you HonFu for helping me communicate better. Thank you KnucleBars for introducing me to the round() function, thank you Arsenic for providing the external link and for providing that codebit. You guys are awesome.
+ 2
For C++, just include the <cmath> header file and use the function round()
+ 2
You're Welcome!
+ 2
I want to show something:
https://www.sololearn.com/discuss/2149084/?ref=app
You see that 'int' doesn't always mean that the 'decimals are cut off'. There's a rest risk that you get a wrong result due to the inevitable computer float inaccuracy.
Better would be to use the 'floor' function to be sure that it's actually the lower value, or 'ceil', if you want the higher.
And after you've gone this far, you could just as well use the 'round' function. ;-)
Another funny thing that came up is that different languages do the rounding slightly differently, which can mean, that a certain method won't work with another language.
For example here:
https://www.sololearn.com/discuss/2104980/?ref=app
So it's actually a bit more tricky that it initially looks!
+ 2
Your welcome Salman Nazeer
+ 2
Thanks again!