This site requires JavaScript, please enable it in your browser!
Greenfoot back
fejfo
fejfo wrote ...

2015/3/25

why is 1/2 0.0 ?

fejfo fejfo

2015/3/25

#
In my code I have :
int dif = platLevel; //get the diffeculty of the level
println("dif="+dif);

double dif_1 = 1/dif;
println("dif_1="+dif_1);

public void println(String text) {
        System.out.println(text);
}
this prints : dif=2 dif_1 = 0.0 why is this ?
davmac davmac

2015/3/25

#
In Java when you divde an integer (int) such as '1' by another integer ('dif'), the division is performed as integer division with an integer result. If you want a double result, divide 1.0 instead:
double dif_1 = 1.0/dif;
fejfo fejfo

2015/3/25

#
I thouth u needed to do
=(int) num1/num2
for integer division
davmac davmac

2015/3/25

#
fejfo wrote...
I thouth u needed to do
=(int) num1/num2
for integer division
Your own result proves that's not the case. If (and only if) both operands are of integer type, the division performed will be an integer division. Your example '(int) num1/num2' will perform integer division only if 'num2' is of integer type.
You need to login to post a reply.