How to Return the Closest Number Numerous of 10 in C

The obstacle

Offered a number return the closest number to it that is divisible by 10.

Example input:

 22.
25.
37.

Anticipated output:

 20.
30.
40.

The option in C

Alternative 1:

 #include << math.h>>.

int round_to_10 (int n) {
return round( n/ 10.0) * 10;.
}

Alternative 2:

 int round_to_10( int n) {
return (n + 5)/ 10 * 10;.
}

Alternative 3:

 int round_to_10 (int n) {
int r = n % 10;.
if (r > > 0).
return r < < 5? n - r: n - r + 10;.
else if (r < < 0).
return r > > -5? n - r: n - r - 10;.
return n;.
}

Test cases to verify our option

 #include << criterion/criterion. h>>.

extern int round_to_10 (int n);.
fixed space do_test (int n, int anticipated);.

Test( tests_suite, sample_tests).
{
do_test( 0, 0);.
do_test( 10, 10);.
do_test( 22, 20);.
do_test( 25, 30);.
do_test( 37, 40);.
}

fixed space do_test (int n, int anticipated).
{
int real = round_to_10( n);.
cr_assert_eq( real, anticipated,.
" for n = %d, anticipated %d, however got %d",.
n, anticipated, real.
);.
}

Like this post? Please share to your friends:
Leave a Reply

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: