Skip to content

How to Return the Closest Number Multiple of 10 in C

The challenge

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

Example input:

22 25 37
Code language: plaintext (plaintext)

Expected output:

20 30 40
Code language: plaintext (plaintext)

The solution in C

Option 1:

#include <math.h> int round_to_10 (int n) { return round(n / 10.0) * 10; }
Code language: C++ (cpp)

Option 2:

int round_to_10(int n) { return (n + 5) / 10 * 10; }
Code language: C++ (cpp)

Option 3:

int round_to_10 (int n) { int r = n % 10; if (r > ) return r < 5 ? n - r : n - r + 10; else if (r < ) return r > -5 ? n - r : n - r - 10; return n; }
Code language: C++ (cpp)

Test cases to validate our solution

#include <criterion/criterion.h> extern int round_to_10 (int n); static void do_test (int n, int expected); Test(tests_suite, sample_tests) { do_test(, ); do_test(10, 10); do_test(22, 20); do_test(25, 30); do_test(37, 40); } static void do_test (int n, int expected) { int actual = round_to_10(n); cr_assert_eq(actual, expected, "for n = %d, expected %d, but got %d", n, expected, actual ); }
Code language: C++ (cpp)

See also  How to Save a Dreamweaver document as UTF8!
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x