How come 1 divide by 2 is less than 0.5 ?!
Hi,
So basically this is a game that you have to hit targets on a grid. every time there's a "hit" the hitCounter is ++ .
in the end of the game it display a message according to your results. (e.g if you hit 4 out of four - 100% the message is "perfect game", if you hit 3 out of four the message is "very good" .... etc.)
well, that's my plan... but the code seems to take me every time to one place.
Assume that in the end hitCounter is 1, NUMBER_OF_TARGETS is always 2 and FIFTY_PERCENT is always 0.5 it will go here:
Code :
else if ((hitCounter/NUMBER_OF_TARGETS) < FIFTY_PERCENT) {
System.out.println("\nSorry, you only hit "+hitCounter+" target(s) out of " + NUMBER_OF_TARGETS);
}
I tested it many times with different numbers. there were times when I hit nothing and it was ok because if(hitCounter== 0) works.
But even if I have perfect game and more than 50% hits it will take me to the same place.
it's probably something in the division, maybe i'm implementing it wrong.
I hope i describe the problem good enough.
Thanks ahead for your help :)
Re: How come 1 divide by 2 is less than 0.5 ?!
Hello raabhim!
I'm assuming that hitCounter and NUMBER_OF_TARGETS are ints, therefore you're using integer division and floating point is not considered. There several ways to make it work. One of them is casting the division to double
Code java:
(double) (hitCounter/NUMBER_OF_TARGETS)
EDIT: My mistake, instead of the division you need to cast one of the variables as Norm suggested.
Re: How come 1 divide by 2 is less than 0.5 ?!
Did you test that expression? The results of the division (0) will be cast to double: 0.0
You need to cast one of variables before the division:
Code :
((double) hitCounter/NUMBER_OF_TARGETS)
Re: How come 1 divide by 2 is less than 0.5 ?!