problem with precision when reading from file

Max S. king@greatfreeworld.org
Thu Sep 16 14:02:00 GMT 2010


On Wed, 2010-09-15 at 17:37 +0300, Anna Sidera wrote:
> Hello, 
> 
> I wrote the following program:
> 
> 
> 
> #include <stdio.h> 
> #include <math.h> 
> #include <stdlib.h> 
> #include <time.h> 
> #include <string.h> 
> 
> int main() 
> { 
> 
> FILE *fp; 
> fp = fopen("test.c", "r"); 
> if (fp == NULL){ 
>     printf("Error opening input file\n"); 
>     exit(1); 
> } 
> 
> float var1, var2, var3; 
> 
> fscanf(fp,"%f",&var1); 
> fscanf(fp,"%f",&var2); 
> fscanf(fp,"%f",&var3); 
> 
> if (var1!=0.01) printf("var1 = %g\n",var1); 
> if (var2!=5) printf("var2 = %g\n",var2); 
> if (var3!=0.6) printf("var3 = %g\n",var3);
> 
> 
> 
> Where test.c contains the following: 
> 
> 0.01 
> 5 
> 0.6
> 
> 
> 
> When I run the program I get the following output: 
> 
> var1 = 0.01 
> var3 = 0.6 
> 
> 
> 
> I expected to get no output. Can you explain what is the problem? 
> 
> Thanks, 
> Anna

Like others have said. You are using two different data types, their
difference being in the amount of precision they hold. (float)a does not
always equal (double)a. Its similar to the difference between char and
int;

What you can do:
1) use only doubles in your code
	double var1, var2, var3; 
and
	fscanf(fp,"%lf",&var1); 

2) use only floats in your code
	if (var1!=(float)0.01) printf("var1 = %g\n",var1);
the implicit double 0.01 being converted to float before use.

3) If you are expecting to have more configuration parameters. Consider
using LUA or another interpreter to handle the parsing of your
configuration files.

I like LUA best but you should search around a bit. It may be a little
overkill for what you are trying to do, but it is simple for both you as
a programmer and for whoever is configuring your program.

heres the link to LUA http://www.lua.org/
Its not as hard to use as it sounds. If you have problems, I found their
IRC community _very_ helpful.

M.S.



More information about the Gcc-help mailing list