GNU GCC compiler
Hello,
I was going through some C exercises when I ran across one that I was having a lot of trouble doing. As it turns out the author's code has an issue and I am stuck on that. The cent value can be off by 1 on certain numbers. It does not appear to be random since it has been affecting the same numbers on Windows and Linux.
A couple of the numbers that I see turn out wrong are: 4.99, 5.99, 1000.99 1000000.99
My biggest question is why does there seem to be a rounding error?
Thanks,
Carl
The short description: Take a monetary value input as variable type float. Put the dollars in a "long" and the cents into a "long" variable type. Then print the value back out using the "long" types.
Author's Code:
Code:
#include <stdio.h>
int main(void)
{
float amounts[5]; /* Stores data values */
long dollars[5];
long cents[5];
printf("Enter five monetary values separated by spaces:\n");
for(int i = 0 ; i<5 ; i++)
scanf("%f", &amounts[i]);
for(int i = 0 ; i<5 ; i++)
{
dollars[i] = (long)amounts[i];
cents[i] = (long)(100.0*(amounts[i]-dollars[i]));
}
printf("\n");
for(int i = 0 ; i<5 ; i++)
printf(" $%d.%02d", dollars[i], cents[i]);
printf("\n");
return 0;
}