Reputation: 116161
celsius = (5.0/9.0) * (fahr-32.0);
Is it just a development choice that the C developers decided upon or is there a reason to this? I believe a float is smaller than a double, so it might be to prevent overflows caused by not knowing what decimal format to use. Is that the reason, or am I overlooking something?
Upvotes: 5
Views: 937
Reputation: 1080
Back in the day of K&Rv1, it was encouraged to use float/double interchangeably being as all expressions with floating-point types were always evaluated using `double' representation, a problem in cases where efficency is paramount. A floating-point constant without an f, F, l, or L suffixed is of type double. And, if the letter f or F is the suffix, the constant is of type float. And if suffixed by the letter l or L, it is of type long double.
Upvotes: 1
Reputation: 6351
The reason that the expression is cast to double-precision is because the literals specified are double-precision values by default. If you specify the literals used in the equation as floats, 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 is:
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
Upvotes: 3
Reputation: 159590
celsius = (5.0/9.0) * (fahr-32.0);
In this expression, 5.0
, 9.0
, and 32.0
are double
s. That's the default type for a floating-point constant - if you wanted them to be float
s, then you would use the F
suffix:
celsius = (5.0F/9.0F) * (fahr-32.0F);
Note that if fahr
was a double
, then the result of this last expression would still be a double
: as Vaibhav noted, types are promoted in such a way as to avoid potentially losing precision.
Upvotes: 27
Reputation: 101151
Floating point constants should have the available highest precision. The result can be assigned to a float without undue trouble.
Upvotes: 0
Reputation: 11436
I think the reason is to ensure that any result can be encompassed. so the natural choice is double as it is the largest data type.
Upvotes: 3