Home > Software design >  VS code is showing different answer for two same code
VS code is showing different answer for two same code

Time:11-29

I run two same code. But it shows different answer.

Code 1:

#include<stdio.h>

int main(){

    float far = 98.6;

    printf("%f", (far-32)*5/9);

    return 0;

}

Code 2:

#include<stdio.h>

int main(){

    float far = 98.6;

    float cel;

    cel = (far-32)*5/9;

    printf("%f", cel);

    return 0;

}

First code gives 36.99999 as output and second code gives 37.00000 as output.

CodePudding user response:

Research FLT_EVAL_METHOD. This reports the intermediate floating-point math allowed.

printf("%d\n", FLT_EVAL_METHOD);

When this is non-zero, the 2 codes may have different output as printf("%f", (far-32)*5/9); can print the result of (far-32)*5/9 using double or float math.

In the 2nd case, (far-32)*5/9); is performed user float or double and then saved as a float and then printed. Its promotion to a double as part of a printf() ... argument does not affect the value.


For deeper understanding, print far, cel, (far-32)*5/9 with "%a" and "%.17g" for greater detail.


In both cases, far is the float value 0x1.8a6666p 6 or 98.599998474121094...

As I see it the first used double math in printf("%f", (far-32)*5/9); and the second used double math too, yet rounded to a float result from cel = (far-32)*5/9;. To be certain we need to see the intermediate results as suggested above.


Avoid double constants with float objects. It sometimes makes a difference.

// float far = 98.6;
float far = 98.6f;

Use double objects as a default. Save float for select speed/space cases. @Some programmer dude.

CodePudding user response:

The difference lies in the types used and the printf call.

Variable-argument functions like printf will promote arguments of smaller types. So for example a float argument will be promoted to double.

The type double have much higher precision than float.

Since in the first program you do the calculation as part of the actual printf call, not storing the result in a variable using less precision, the compiler might perform the whole calculation using double and increasing the precision. Precision that will be lost when you store the result in cel in the second example.

Unless you have very specific requirements, you should generally always use double for all your floating-point variables and values and calculations.

  •  Tags:  
  • c
  • Related