fscanf and rounding problems

This is a discussion on fscanf and rounding problems within the C Programming forums, part of the General Programming Boards category; Hi all, I am new to the forum and I have to admit that is very useful as I have ...

  1. #1
    Registered User
    Join Date
    Jul 2005
    Posts
    2

    Unhappy fscanf and rounding problems

    Hi all,

    I am new to the forum and I have to admit that is very useful as I have seen so far.

    I face the following problem.

    I have .txt file which contains the following lines:

    ---------------
    0.553842
    0.643939
    0.416941
    0.876019
    0.234986
    0.429439
    0.680470
    0.322184
    0.600104
    0.131541
    ---------------

    I use GSL library and I assign this values into a vector called Y by doing this:
    Code:
    FILE * f1 = fopen("data.txt","r");
    
    for (i=0; i<n; i++) { 
    
        fscanf(f1,"%lf ", &(Y->data[i]));
        
        fscanf(f1,"\n");
        
    }
    when I print the values of the vector I get this:

    Code:
    for ( ... ) {
    
          printf("%.20lf\n", Y->data[i])
    
    }
    and I get this:

    0.55384199999999995000
    0.64393900000000004000
    0.41694100000000001000
    0.87601899999999999000
    0.23498600000000000000
    0.42943900000000002000
    0.68047000000000002000
    0.32218400000000003000
    0.60010399999999997000
    0.13154099999999999000

    although I was expecting to get something like:

    0.55384200000000000000
    0.64393900000000000000
    ....

    Any ideas why is this happening? Am I doing something wrong?

    thanks in advance,
    THeo.

  2. #2
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,047
    floats and doubles always do that.

  3. #3
    Registered User
    Join Date
    Jul 2005
    Posts
    2
    thanks dwks for you reply.

    so, isn't there any solution to the "problem"?

  4. #4
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,047
    You could use fgetc() to read in each char and store it in a string.

  5. #5

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21