0

There is a very simple thing I cannot accomplish in C. I just want to make a simple division. The result is rounding the number.

Here is the code

#include <stdio.h>
#include <math.h>

int main()
{
    float a = 5 / 2;

    printf("%0.2f", a);

    return 0;
}

The result I'm getting is 2.00 and I want it to be the actual 2.50.

Student
  • 805
  • 1
  • 8
  • 11
Cruz
  • 1
  • 1

1 Answers1

1

You get the correct result by writing the numbers in your division as floats:

float a = 5.0f / 2.0f;

Another way would be typecasting:

float a = (float)5 / 2;

In your code, the numbers are treated as ints and only converted to float afterward. This gives the wrong rounding.

Student
  • 805
  • 1
  • 8
  • 11
Georg
  • 94
  • 4