Search code examples
cfloating-pointfloating-accuracyatof

Conversion problem in ansi c


Possible Duplicates:
Floating point inaccuracy examples
Is JavaScript's Math broken?

I need to convert some data from txt file into double value and I'm using this function for this : atof . The problem is that the value which must be convert is 5.550000 and the atof function return 5.5499999999999998 and this is a problem because I must calculate the GPA with this number and the reault is not precise. This is the function which read the data from the txt file:

void readNext(FILE* file,Lab* lab)
{
    char line[100];
getline(file,line,100);
if (strcmp(line,"") == 0)
{
    lab->is_null = 1;
    return;
}
strcpy(lab->date,line);
getline(file,line,100);
lab->presence = atoi(line);
getline(file,line,100);
strcpy(lab->num_work,line);
getline(file,line,100);
lab->mark_work = atof(line);
getline(file,line,100);
lab->test_work = atof(line);
getline(file,line,100);
lab->current = atof(line);
getline(file,line,100);
lab->status_work = atoi(line);
getline(file,line,100);
}

Solution

  • drhirsch is correct - 5.55 cannot be exactly represented in binary floating point (in the same way that 1 ÷ 7 cannot be exactly represented in decimal).

    However, for your purposes, this shouldn't be a problem, because a float definitely can store 5.55 accurate to three places, which is the number you have. This just means that you need to use the correct format when printing - in this case, %.3g. When you calculate the GPA, your calculations will still be accurate to three places, because the calculation of an average doesn't cause catastrophic cancellation.