0

I just wanted to test simple operators in different data types in C and there is an unexpected output

INPUT


    printf("%.2f \n", 10.0 + 4.0 + 5);
    printf("%d \n", 10 + 4);
    printf("%d \n", 12 * 5);
    printf("%.5f \n", 12 * 5);
    

OUTPUT

19.00 
14 
60 
19.00000 

I don't understand why I got 19.00000 output when I tried to multiply 12 * 5

1 Answers1

-1

You are getting the result of because printf("%.5f \n", 12 * 5); multiplies an integer 12 with integer 5 but returns a float. So the output you get is a float. However, to return float value, you can multiply with float value(s) or type cast them as float.

Some examples,

printf("%.5f \n", 12.0 * 5.0);
printf("%.5f \n", 12.0 * 5);
printf("%.5f \n", (float)12 * 5);
  • The code makes sense, the wording doesn't. – Eugene Sh. Dec 22 '22 at 18:50
  • `12 * 5` has type `int` not `float`, and the `%f` operator expects `double`. The problem an `int` is passed where at _runtime_ it is interpreted as a `double` - worse an `int` is typically a narrower type than a `double` so it is not even deterministic behaviour. It is misleading to cast it to `float` since it will in any event be converted to `double` (https://en.cppreference.com/w/cpp/language/variadic_arguments). Better example: `printf( "%.5f \n", (double)12 * 5);` – Clifford Dec 22 '22 at 19:21