Mail Archives: djgpp/2000/08/01/13:30:26
Radical NetSurfer wrote:
> Why does the following program INCORRECTLY display
> the fractional part?
[snip excessive number of header files]
> int main(int argc, char **argv) {
> double i, f;
> double v, y;
>
> printf("Observe the \"Rounded\" Value of Fint below:\n");
> printf("Use ESC to exit.\n\n");
>
> for(v=0.0; v< 10; v+=0.1) {
> f = modf(v, &i); // fractional = modf(argument, &integral);
> if ( f <0.5 ) y = floor(v);
> else y = ceil(v);
>
> printf("Value: %lf Fint: %lf Int: %lf Frac: %lf\n",
%lf is complete nonsense. The l is used for long ints, so using
it for floating point numbers is meaningless. Just %f suffices for
doubles.
> v, y, i, f );
> if ( getch() == 27 ) break;
> }
>
> return (0);
> } //main
> ------------------------------------------------------------------------------------------------------
> well?
Well what? When you post something that you think is behaving
incorrectly it would be helpful if you said what you expected it to do.
If you are referring to the fact that the fractional part is sometimes
shown as 1.000000, then that's not at all surprising. 0.1 cannot be
represented exactly as a binary floating point number, so some of the
numbers that you might expect to be integers are actually slightly off.
Those that are slightly less than an integer will have a fractional
part slightly less than 1, and this will show as 1.000000 when you
display it to 6 decimal places.
Floating point numbers are only approximate, and you will make many
mistakes if you don't realise this. Most of the time it's not a
problem, as long as you're careful. But if you do want to do exact
calculations with rationals then consider downloading GMP, which
Richard Dawe has kindly ported to DJGPP.
S.
- Raw text -