Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: How come 1 divide by 2 is less than 0.5 ?!

1. ## 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:

```
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.

2. ## 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
`(double) (hitCounter/NUMBER_OF_TARGETS)`

EDIT: My mistake, instead of the division you need to cast one of the variables as Norm suggested.

3. ## The Following User Says Thank You to andreas90 For This Useful Post:

raabhim (May 1st, 2012)

4. ## 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:
`((double) hitCounter/NUMBER_OF_TARGETS)`

5. ## The Following 2 Users Say Thank You to Norm For This Useful Post:

andreas90 (May 1st, 2012), raabhim (May 1st, 2012)

Perfect!
Thanks guys