public class Solution { public static void main(String[] args) { System.out.println(getWeight(888)); } public static double getWeight(int weightEarth) { double P = ((weightEarth / 100) * 17); return P; } } 

This is what I get as a result: 136.0 How to get 150.96?

  • (((double)weighEarth/100)*17); - rjhdby

2 answers 2

Since weightEarth is of type int , and 100 is also an integer type, the result of their division will also be int .

Those. int/int=int => 888/100=8

To get a different result from this, one or both operands must first be cast to double or float

It is possible so:

 (((double)weighEarth/100)*17); 

And you can

 ((weighEarth/100.)*17); 

    The error is as follows:

    weightEarth / 100

    Need to fix on

     weightEarth / 100.0 

    Because in the original case, the division into an integer e occurs, and in the second by a fractional number. As you remember, the result of dividing two integer values ​​in java is integer . But if the numerator and / or denominator is fractional, the result will also be fractional .
    In more detail it is possible to read about implicit type conversion in specifications .

    Example: http://ideone.com/iNbd5J

    • even more "understandable" than my comments. Bravo - rjhdby
    • @rjhdby, I already added a link to ideone. But in general, it seems to be understandable :) - Qwertiy
    • For the first time I see it, and even more, I find out that only a point was needed. Magic ... - hellog888 February
    • one
      @ArtemKonovalov, please post your add-ons with a separate answer, and return this one as it was. PS: I asked a question on the meta . And from what 100.0 instead of 100. ? - Qwertiy
    • one
      because 100. is less obvious than 100.0 and creates more questions. - Artem Konovalov