tags:

views:

505

answers:

5

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?

+3  A: 

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.

Vaibhav
The only reason the natural choice is a double is because of what @Shog9 said: there are doubles in the math so it is being evaluated as a double.
sixlettervariables
+1  A: 

Floating point constants should have the available highest precision. The result can be assigned to a float without undue trouble.

dmckee
+24  A: 
celsius = (5.0/9.0) * (fahr-32.0);

In this expression, 5.0, 9.0, and 32.0 are doubles. That's the default type for a floating-point constant - if you wanted them to be floats, 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.

Shog9
+3  A: 

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
hoyhoy
A: 

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.

amaterasu