Saturday, March 4, 2023
HomeSoftware EngineeringThe best way to Return the Closest Quantity A number of of...

# The best way to Return the Closest Quantity A number of of 10 in C

## The problem#

Given a quantity return the closest quantity to it that’s divisible by 10.

Instance enter:

``````22
25
37
``````

Anticipated output:

``````20
30
40
``````

Possibility 1:

``````#embrace <math.h>

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

Possibility 2:

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

Possibility 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;
}
``````

## Take a look at instances to validate our answer#

``````#embrace <criterion/criterion.h>

extern int round_to_10 (int n);
static void do_test (int n, int anticipated);

Take a look at(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 anticipated)
{
int precise = round_to_10(n);
cr_assert_eq(precise, anticipated,
"for n = %d, anticipated %d, however bought %d",
n, anticipated, precise
);
}
``````
RELATED ARTICLES