Re: problem with precision when reading from file

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



 On 9/15/2010 7:37 AM, 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
Did you mean to try

if (var1!=0.01f) printf("var1 = %g\n",var1);
if (var3!=0.6f) printf("var3 = %g\n",var3);

or possibly to convert var1 and var3 back to short char strings and compare those?

0.01 and 0.6 are constants of type double and will have typically 29 more bits precision in their
 conversion from decimal to binary representation than your conversions to type float.




--
Tim Prince



[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux