0

I'm trying to divide two numbers together and print the answer but the compiler always gives 1.000000 as the answer, Iv'e tried changing the literals but the answer is still the same somewhat.

Here is my code:

#include <stdio.h>
int main()
{
float a = 20 / 12;
printf ("%f", a);
}

Any ideas why this happens and how to get the right answer?

4 Answers4

4

Change

float a = 20 / 12;

to

float a = 20 / 12.f;

20 / 12 is an integer division.

ouah
  • 142,963
  • 15
  • 272
  • 331
4

typecast at least one of value as float type.

float a=(float)20/12;
Rustam
  • 6,485
  • 1
  • 25
  • 25
2

You are performing integer division, if I change

float a = 20 / 12;

to

float a = (float) 20 / 12;

I get

1.666667
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
2

What you are doing is integer division, i.e.

float a = 20/12 ----- gives you the integer quotient.

In order to get a float quotient you can do it like this

float a = 20/12.0;    
or
float a = 20.0/12;
Abhishek Choubey
  • 883
  • 6
  • 16