Rounding errors using doubles?
Dima Volodin
dvv@dvv.ru
Wed Mar 31 23:46:00 GMT 1999
Sam Lantinga wrote:
> On a Pentium II, the following code gives an incorrect result when using
> doubles, but a correct result when using floats:
>
> #include <stdio.h>
>
> #ifdef USE_FLOAT
> /* This works */
> typedef float percentage_type;
> #else
> /* This doesn't */
> typedef double percentage_type;
> #endif
>
> main()
> {
> int value = 86;
> percentage_type percentage;
>
> printf("Starting Percentage is: %d\n", value);
> percentage = ((percentage_type)value)/100.0;
> printf("Ending Percentage is: %d\n", (int)(percentage * 100.0));
Your code is broken here. What you need is
printf("Ending Percentage is: %d\n", (int) floor(percentage * 100.0 + 0.5));
And, BTW, converting to int is _not_ rounding.
> -Sam Lantinga
Dima
More information about the Gcc
mailing list