Kelly Mah wrote:
Sorry if I got the wrong group.
I seem to be running into a rounding issue on a Linux AS2.1 box using
gcc 2.95. This program always returns 419 on Linux, but on a Solaris
machine, I get the expected 420 output.
------------------------------------------------
#include <math.h>
There is no point in including headers you don't use.
#include <stdio.h>
int main()
{
double x = 0.0010;
double y = 0.420;
int result = 0;
result = (int)(y/x);
printf("y/x is %d\n",result);
return 0;
}
------------------------------------------------
Anybody know why?
This is yet another variation on the never-ending question: "I don't
understand floating-point arithmetic and am too lazy to check the FAQ.
Why don't floating-point numbers have infinit precision?" Try the
following on your computer:
#include <stdio.h>
#include <float.h>
int main(void)
{
double x = 0.0010;
double y = 0.420;
long double xl = 0.0010L;
long double yl = 0.420L;
float xf = 0.0010f;
float yf = 0.420f;
printf("In all cases, bogus precision is printed;\n"
"xxx_DIG + 4 is used rather than xxx_DIG\n\n");
printf("y/x = %.*g/%.*g = %.*g, (int)(y/x)= %d\n", DBL_DIG + 4, y,
DBL_DIG + 4, x, DBL_DIG + 4, y / x, (int) (y / x));
printf("yl/xl = %.*Lg/%.*Lg = %.*Lg, (int)(yl/xl)= %d\n",
LDBL_DIG + 4, yl, LDBL_DIG + 4, xl, LDBL_DIG + 4, yl / xl,
(int) (yl / xl));
printf("yf/xf = %.*g/%.*g = %.*g, (int)(yf/xf)= %d\n", FLT_DIG + 4,
yf, FLT_DIG + 4, xf, FLT_DIG + 4, yf / xf, (int) (yf / xf));
return 0;
}
In all cases, bogus precision is printed;
xxx_DIG + 4 is used rather than xxx_DIG
y/x = 0.4199999999999 999845/0.0010000000000 00000021 = 420, (int)(y/x)= 420
yl/xl = 0.4199999999999 999999827/0.0009999999999 999999999133 = 420,
(int)(yl/xl)= 420
yf/xf = 0.4199999869/0.001000000047 = 419.9999695, (int)(yf/xf)= 419