The challenge

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

Example input:

1
2
3
22
25
37

Expected output:

1
2
3
20
30
40

The solution in C

Option 1:

1
2
3
4
5
#include <math.h>

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

Option 2:

1
2
3
int round_to_10(int n) {
  return (n + 5) / 10 * 10;
}

Option 3:

1
2
3
4
5
6
7
8
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 validate our solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#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(0, 0);
  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
  );
}