### how do you round numbers?

for my assignment i have to round three different numbers in a function. the function only receives one integer, a number from 0-100. i have to round it to the nearest 10. for example, if i send the function 22, it will return 20; if i send in 78, it will return 80. im not sure how to do this. i tired a random number but it didnt work. this is what i put in the function:
 1234567 int roundscore (int score) { if (score >= 15 && score <= 25) score = 20; else score=10; return score; }
Hint: play around with the % operator.
Try this :

 123456789101112 int roundscore(int score) { int r; r = score%10; if( r>=5) score = score + (10-r); else score = score - r; return r; }

Here r is the remainder obtained when divided by 10.
When r>=5, score has to be rounded to upper bound.
If it is less than 5 it has to be rounded to lower bound.
Last edited on
This is one way:
 12345 inline int round( int number ) { const int delta = number < 0 ? -5 : 5 ; return ( number + delta ) / 10 * 10 ; }
thank you everyone.

@sandeep. it worked fine when i returned score and not r.
Topic archived. No new replies allowed.