Why does this C code create a double instead of a float?

celsius = (5.0/9.0) * (fahr-32.0);

Is it just a development choice that C developers have decided or is there a reason for this? I believe that float is less than double, so overflow caused by not knowing which decimal format to use can be prevented. Is this the reason, or am I missing something?

+4
source share
5 answers

I think the reason is to ensure that any result can be covered. therefore, the natural choice is double, as it is the largest data type.

+4
source
 celsius = (5.0/9.0) * (fahr-32.0); 

In this expression, 5.0 , 9.0 and 32.0 are double s. This is the default type for a floating point constant - if you want them to be float s, then you would use the suffix F :

 celsius = (5.0F/9.0F) * (fahr-32.0F); 

Note that if fahr was double , the result of this last expression will still be double : as Vaibhav noted, types are promoted in such a way as to avoid potential loss of precision.

+26
source

The reason the expression is applied to double precision is because the specified literals are double precision values ​​by default. If you specify the literals used in the equation as a float, the expression will return a float. Consider the following code (Mac OS X using gcc 4.01).

 #include <stdio.h> int main() { float celsius; float fahr = 212; printf("sizeof(celsius) ---------------------> %d\n", sizeof(celsius)); printf("sizeof(fahr) ------------------------> %d\n", sizeof(fahr)); printf("sizeof(double) ----------------------> %d\n", sizeof(double)); celsius = (5.0f/9.0f) * (fahr-32.0f); printf("sizeof((5.0f/9.0f) * (fahr-32.0f)) --> %d\n", sizeof((5.0f/9.0f) * (fahr-32.0f))); printf("sizeof((5.0/9.0) * (fahr-32.0)) -----> %d\n", sizeof((5.0/9.0) * (fahr-32.0))); printf("celsius -----------------------------> %f\n", celsius); } 

Output:

 sizeof(celsius) ---------------------> 4 sizeof(fahr) ------------------------> 4 sizeof(double) ----------------------> 8 sizeof((5.0f/9.0f) * (fahr-32.0f)) --> 4 sizeof((5.0/9.0) * (fahr-32.0)) -----> 8 celsius -----------------------------> 100.000008 
+3
source

Floating-point constants should have the highest possible accuracy. The result can be assigned to the float without unnecessary problems.

+1
source

One day, K & Rv1 recommended using float / double, interchangeably, since all expressions with floating-point types were always evaluated using the "double" representation, a problem in cases where efficiency is of paramount importance. A floating point constant without the suffix f, F, l or L is of type double. And, if the letter f or F is a suffix, the constant is of type float. And if the suffix is ​​the letter l or L, it is of type long double.

+1
source

Source: https://habr.com/ru/post/1276506/


All Articles