So, I'm doing a fighting game in java and I have this equation that always returns zero.
int x = 90/100*300;
It should be 270 but it returns zero. :|
So, I'm doing a fighting game in java and I have this equation that always returns zero.
int x = 90/100*300;
It should be 270 but it returns zero. :|
You're doing integer calculation, so 90/100 results in 0.
If you write it 90.0/100*300
, the calculations will be done with doubles (then you'll need to cast it back to int if you want).
The problem here is it first divides 90/100
which is actually 0.9
however since it is an int
type the value is 0
and then when you multiply 0
with 300
the output is 0
.
90/100 is 0 remainder 90.
You can fix this by re-arranging the values
int x = 90 * 300 / 100; // 270
Do the multiplications before the divisions and as long as you don't get an overflow, this will be more accurate.
Java in this case carries out the multiplication/division in order.
It also interpretes each number as integers.
So, 90/100 = 0.9 and it gets truncated to 0.
and 0 * 300 = 0.
So you end up with 0
You use integer
datatype you use float
or double
datatype and get proper answer of this equation. Integer datatype only decimal value answer return but float and double datatype return answer with floating point then must use float or double datatype in this equation.