0

Why is this code giving 0.0 as answer?

public static void main(String[] args) {
    float ans = (480/1080);
    System.out.println(ans);
}
Eran
  • 387,369
  • 54
  • 702
  • 768
Linojan
  • 21
  • 3

2 Answers2

3

You are dividing two integers, so the result is integer. 480/1000 < 1 and is therefore truncated to 0. Then the result is cast to float to be stored in the float variable.

To divide the numbers as floats, cast one of them:

float ans = ((float)480/1080);
Eran
  • 387,369
  • 54
  • 702
  • 768
0

Try this.. Here both numbers will be float so You'll get float value..

 float ans = ((float)480/(float)1080);
            System.out.println(ans);

Output:
0.44444445

SonalPM
  • 1,317
  • 8
  • 17