0

The code that I have,

public static void main(String[] args) {
    int x = 27;
    int y = 5;
    double z = x / y;
    System.out.println(" x = " + x + " y = "+y +" z = "+z);
}

In the above code I know that to print out the decimal place .4 for the variable z we have to use printf, but my question is why does the variable z is not storing the 5.4 and just storing 5? I mean int / int then the out put is stored in a double, which is perfectly capable of holding decimal values but it is not, what is the logic?

Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
noobprogrammer
  • 513
  • 5
  • 14
  • possible duplicate of [Getting double value from the quotient of integers](http://stackoverflow.com/questions/9095399/getting-double-value-from-the-quotient-of-integers) See also: http://stackoverflow.com/questions/3144610/java-integer-division-how-do-you-produce-a-double – assylias Nov 14 '12 at 06:25

4 Answers4

3

You need to cast one of the operands to a double

double z = (double) x / y;

The reason is x / y stand-alone is an int, so it is really evaluating as 5 and then parsing to a double.

John
  • 2,675
  • 2
  • 18
  • 19
  • 1
    No, he needs to cast *one of the operands* to a double. Casting the result of the operation is what already happens. Your code does what is necessary but you've mis-described it. – user207421 Nov 14 '12 at 05:59
3

You have to cast the integers before you divide I believe.

Like this,

double z = (double) x / (double) y;
Austin
  • 4,801
  • 6
  • 34
  • 54
3

This is happening because the values that you are dividing with are int and not double and they are not going to output the decimal places, to be more clear take this for example

double z = 27 /5; same as yours

double z = 27.0/5.0; now z = 5.4; So this shows that the datatype that you are performing calculation with also should be the same as the datatype you are expecting the output to be.

JackyBoi
  • 2,695
  • 12
  • 42
  • 74
1

What you're doing in the line:

double z = x / y;

is integer division, and then you convert the outcome to double

Neowizard
  • 2,981
  • 1
  • 21
  • 39