+ 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

3rd Feb 2020, 11:10 AM
Salman Nazeer
Salman Nazeer - avatar
10 Réponses
+ 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; }
3rd Feb 2020, 12:20 PM
Arsenic
Arsenic - avatar
+ 4
I've shared it now. I apologise for not including it in the original question.
3rd Feb 2020, 11:36 AM
Salman Nazeer
Salman Nazeer - avatar
+ 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'.
3rd Feb 2020, 11:25 AM
HonFu
HonFu - avatar
+ 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.
3rd Feb 2020, 12:34 PM
Salman Nazeer
Salman Nazeer - avatar
+ 2
For C++, just include the <cmath> header file and use the function round()
3rd Feb 2020, 11:14 AM
KnuckleBars
KnuckleBars - avatar
3rd Feb 2020, 12:27 PM
KnuckleBars
KnuckleBars - avatar
+ 2
You're Welcome!
3rd Feb 2020, 12:35 PM
KnuckleBars
KnuckleBars - avatar
+ 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!
3rd Feb 2020, 12:44 PM
HonFu
HonFu - avatar
+ 2
Your welcome Salman Nazeer
3rd Feb 2020, 12:48 PM
Arsenic
Arsenic - avatar
+ 2
Thanks again!
3rd Feb 2020, 4:24 PM
Salman Nazeer
Salman Nazeer - avatar