This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Why does 8 equal 8.5? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why does 8 equal 8.5?" Watch "Why does 8 equal 8.5?" New topic
Author

Why does 8 equal 8.5?

Kevin Tysen
Ranch Hand

Joined: Oct 12, 2005
Posts: 255
Part of the program I'm writing looks like this:

int counter
// lines that set the value of counter to 17
if ((counter/2)==((int)(counter/2))){
return true;
}else{
return false;
}

I get a return of true. It seems to me that counter/2 should equal 8.5 and that (int) (counter/2) should equal 8 and that 8.5 and 8 are not equal. Why do I get a return value of true?
This is the way I find out if an integer is divisible by two. I've been programming in BASIC all my life and recently tried out java. Is there a better way in java to find out if an integer is divisible by another integer?
Max Habibi
town drunk
( and author)
Sheriff

Joined: Jun 27, 2002
Posts: 4118
Kevin,

a quick question: is 8.5 an int?


Java Regular Expressions
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39478
    
  28
There are Five arithmetic operators in Basic, or at least there were when I last programmed Basic back in the 1970s [ ], namely +-*/ and **, but you could use ^ instead of **.
There are Five arithmetic operators in Java, which are +-*/ and %.

% returns the remainder when you divide one number by another. Try that.

Basic is [or at least, was] an un-typed language; if you have x = 3, then it just takes x as a number, without checking whether you want it to be a "real" number, ie one with a decimal point in, or an integer. Java is strongly typed; you have to tell the compiler what format every variable takes; if it is an integer, you have to say so.
And as for 8.5, the rules of integer arithmetic were the same in the 1970s as they are nowadays, and one of them is that integer division returns an integer result, not a fractional result. Try it out: using integer arithmetic work out 7 / 2 * 2, then 7 * 2 / 2.

And there is no need for the if statements. All you have to do is write
It will work out true and false for you.

CR
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Why does 8 equal 8.5?