Search code examples
cfloating-pointtype-conversionansi-c

Floating point conversion in ANSI C


Given the following ANSI C code, I wonder about the results:

main() {
  int a = 19.4 / 9.7;               // result = 2
  float b = (int) 19.4 / (int) 9.7  // result = 2.000000, why?
  float c = (int) 9.7;              // result = 9
}

I understood that C will cut off all decimal places on the conversion to int but my logic has a flaw if I see the second line. If the decimal places were cut, the result must be 2.11111.

How is the floating point conversion done in ANSI C?


Solution

  • In standard C, literals such as 19.4 and 9.7 are assumed to be double unless you specify otherwise (eg. 19.4F, 9.7F).

    The compiler will use either the integer division function to compute x / y (if both x and y are of int (compatible) type) or the floating point division function to computer x / y if atleast one of x and y are a floating point type.

    float b = (int) 19.4 / (int) 9.7 // result = 2.000000, why?

    You are asking for 19.4 to be cast to int, and 9.7 to be cast to int, effectively asking the compiler to compute the integer division of 19/9 = 2, which is then promoted to float for storage in b. 2 becomes 2.0.

    .PMCD.