• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

How does this program work?

Status
Not open for further replies.

Vieo

Member
My first roman numeral converter program was supposed to convert numbers into roman numerals(I didn't get it working in the end, but I recently built one that converts roman numerals to numbers instead. =P). One of the methods I was going to use in the program was a technique for rounding numbers. I couldn't find an already existing C function for rounding so I posted on these boards and someone replied with something like...

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

#include<stdio.h>
void main()
{
int x = 76, num;
num = roundto(x);
printf("%d\n", num);
}



How exactly does this program work? It gives x the value of 76, it then gives num the value of x after it's been sent to the function roundto then displays num, which is number 80. What I don't understand is how is the function getting the rounding done?
It takes 76, adds 5 to it, then divides it by 10. You get 8.1, right? Then it multiplies 8.1 and you end up with 80? How do you get 80? Isn't 8.1 * 10 just 81.0?

Arrgh! I'm so confused!
 

Argyle

Member
The variables are ints, not floats, so what happens for 76...

76 + 5 = 81
81 / 10 = 8 (.1 dropped because it's an integer)
8 * 10 = 80
 

Vieo

Member
Ok. That explains it!

If I change the 10 in the roundto function to 100, I guess it rounds to the nearest 100th.
 
Status
Not open for further replies.
Top Bottom