noobprogrammer
noobprogrammer

Reputation: 523

Double not storing proper value

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?

Upvotes: 0

Views: 810

Answers (4)

Neowizard
Neowizard

Reputation: 3017

What you're doing in the line:

double z = x / y;

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

Upvotes: 1

JackyBoi
JackyBoi

Reputation: 2773

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.

Upvotes: 3

Austin
Austin

Reputation: 4929

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

Like this,

double z = (double) x / (double) y;

Upvotes: 3

John
John

Reputation: 2755

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.

Upvotes: 3

Related Questions