0

I have a piece of code that looks like this:

float nb = 100 / 42;
printf("%.2f", nb);

which I expect to print out 2.38, but instead it prints out 2.00.

The 42 is just an example. In the original code it's a variable.

Dave Cousineau
  • 12,154
  • 8
  • 64
  • 80
Saryk
  • 345
  • 1
  • 12

1 Answers1

0

You need to specify the numbers as floating point themselves. Try this:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv)
{
    float nb = 100.0/42.0;
    printf("%.2f\n", nb);
    return 0;
}
CDahn
  • 1,795
  • 12
  • 23
  • Note that `100.0/42.0` is a `double`, which is then downcast to `float`, and then upcast back to `double` for `printf()`. So the conversion may be unnecessary. – Dietrich Epp Jul 25 '14 at 01:10