0

Can somebody explain the output of the following code: http://cpp.sh/9dy44

Why is the last line always 0.17?

float a = 17, b = 100;

printf("%f\n", 17/100);
printf("%f\n", a/b);
printf("%f\n", 17/b);
printf("%f\n", 17.0f/b);
printf("%f\n", a/100);
printf("%f\n", a/100.0f);
printf("%f\n", 5/100);

output

0.000000
0.170000
0.170000
0.170000
0.170000
0.170000
0.170000
hicksi
  • 43
  • 3
  • 3
    UB here `... "%f\n", 17/100);` allready all the rest is (bad) luck, – alk Oct 28 '18 at 12:48
  • Possible duplicate of [Printing int as float in C](https://stackoverflow.com/questions/16607628/printing-int-as-float-in-c) – Cepheus Oct 28 '18 at 12:50

2 Answers2

2

This is called Undefined Behaviour , don't try to understand why this is happening , because as the name suggests , it is undefined !. The undefined behaviour happens because you are trying to print a double but you're passing two integers . Note that you are also getting a warning :

14:25: warning: format '%f' expects argument of type 'double', but argument 2 has type 'int' [-Wformat=]

Change last line to this:

    printf("%f\n", 5.0/100);

And it will work as expected .

sagi
  • 40,026
  • 6
  • 59
  • 84
  • I was expecting the output of last line would bei 0, is there an explanation why it sticks with the 0.17? – hicksi Oct 28 '18 at 12:49
  • 1
    Each comipler you will use may have different behaviour , one will print 0 , the other 0.17, and another one will print 2. Why ? Becuase it is undefined . – sagi Oct 28 '18 at 12:50
  • if you're instested in knowing more - google : `C Undefined behaviour` , there are plenty articles on this subject . – sagi Oct 28 '18 at 12:52
  • okay thanks so far... i was just wondering why the behavior was so different between the first and last printf – hicksi Oct 28 '18 at 12:55
  • 1
    It is detrimental to tell somebody “don’t try to understand.” While behavior not defined by the C standard may be perplexing and is not strictly needed to write a working C program, understanding it nonetheless has benefits. It provides insights into how compilers, processors, and other system components work, and that insight both helps diagnose bugs and learn about things outside of pure C. In this case, the floating-point value left in the register for passing floating-point arguments by printing `a/b` or `17.0f/b` remains in the register for subsequent calls to `printf`, so it is reused. – Eric Postpischil Oct 28 '18 at 13:23
0

Because You are dividing integers and than trying to print (the integer result as) a float value

Try This

// Example program
#include <stdio.h>

int main()
{
    float a = 17, b = 100;

    printf("%f\n", 17.0/100);
    printf("%f\n", a/b);
    printf("%f\n", 17/b);
    printf("%f\n", 17.0f/b);
    printf("%f\n", a/100);
    printf("%f\n", a/100.0f);
    printf("%f\n", 5.00/100);

    return 0;
}
Usama
  • 336
  • 1
  • 14