wje_lq |
08-04-2009 12:42 PM |
Quote:
Originally Posted by neonsignal
(Post 3630499)
Floating point numbers can only be represented with a certain amount of precision.
In C, you would normally use the 'double' type for floating point numbers, which has more precision than the 'float' type.
|
Yes, this fixes the problem.
Quote:
Originally Posted by neonsignal
(Post 3630499)
(use "%lf" when formatting the output in printf).
|
The man page does not assign any meaning to %lf. %f is already adequate for variables of type double. To demonstrate, you'll get this output:
Code:
fz is 1946.49804687500000000000000000000000000
dz is 1946.49808502197265625000000000000000000
if you run this bash script:
Code:
#!/bin/sh
cat > 1.c <<EOD; gcc -Wall 1.c -o 1; ./1
#include <stdio.h>
int main(void)
{
float fa, fb, fz;
double da, db, dz;
fa=1946.498046875; fb=0.00003814697265625; fz=fa+fb;
da=1946.498046875; db=0.00003814697265625; dz=da+db;
printf("fz is %40.35f\n",fz);
printf("dz is %40.35f\n",dz);
return 0;
} /* main() */
EOD
If you need even greater precision, use variables of type long double. Constants should be followed by the letter "L", either upper or lower case. (I recommend you use upper case "L", because lower case "l" looks too much like the numeral 1.) The format is "Lf" (upper case; lower doesn't work).
|