1

I have a problem with this

System.out.print((9/5) * 3);

I expects the result 5.4 but it returns 3. Why is this happening?

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Pushpendra Kumar
  • 1,721
  • 1
  • 15
  • 21

4 Answers4

8

9/5 is evaluated in integer arithmetic, so it's equal to 1.

Writing 9.0 / 5 * 3 is a common fix. (Promoting one of the coefficients in the term to a double forces the evaluation to take place in double precision floating point.)

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

System.out.print((9.0/5) * 3);

Ramesh Khadka
  • 484
  • 1
  • 7
  • 19
1

In java when you make division of integers it will return an integer not a real number :

9/5 return 1 instead of 1.8

to solve your problem you have two solutions :

  1. use a real number instead so you have to use 9.0/5
  2. or you can cast the number to double ((double)9/5) * 3
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
1

All the numbers are integer there so it will give integer result you may make 9.0 or 5.0 to get that answer... As given below..

System.out.print((9.0/5) * 3); OR
System.out.print((9/5.0) * 3);
Vikas Suryawanshi
  • 522
  • 1
  • 5
  • 12
  • I'd be inclined to remove the redundant parentheses since (i) I'm dogmatic about that, and (ii) you are vulnerable to someone refactoring to `(9 / 5) * 3.0`. But have an upvote all the same. – Bathsheba Jun 08 '17 at 12:32