1

I have two long long (int) values, and I want to print their division in float format with 3 digits precision. I have already read printf and long double , but all those suggestions lead to nan as the result of printf. E.g.

  long long a = 123123123;
  long long b = 123123124;
  printf("%d\n", b/a);
  printf("%.3f", b/a);

The first print will output 1 (as expected), but the second 0.000 instead of 1.xxx

Community
  • 1
  • 1
joeo
  • 25
  • 4

1 Answers1

1

Except for the first one, printf doesn't check the passed arguments or the number of formatting arguments of the string vs the arguments (most compilers can warn you about problems, but that's not guaranteed)

b/a is a long long type.

So even if the first printf kind of works, it would be better with

printf("%lld\n", b/a);

second printf doesn't work at all because argument is interpreted as a double, but not converted (although passing a float would also work: How does printf and co differentiate beetween float and double) , due to the varadic nature of the printf function (you can virtually pass anything as argument, so it's not safe). You have to convert it to double explicitly for instance like this:

printf("%.3f", (double)b/a);

Note that (double)(b/a) would also work but you'd lose the decimal part

Community
  • 1
  • 1
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219