February 21st, 2008, 11:29 PM
|
#1 (permalink)
|
| Ultimate Member
Join Date: Nov 2004 Location: Provo, UT
Posts: 1,337
| Wiley While loops
Well, I have this beautiful program written that elegantly taked decimals and takes them to a binary state. At least I think so. For some reason, my algorithm hangs on even numbers! Odds concatenate right and come out correct. Why? Code:
while(decimal != 0)
{
if((decimal%2) == 0)
binary = binary.concat("0");
System.out.println("evens are concatenating");
if((decimal%2)!= 0)
binary = binary.concat("1");
System.out.println("odds are concatenating");
decimal--;
decimal /= 2;
}
My output looks like the following for odds: Code: Input you number please:
:3
As a decimal: 3.0
evens are concatenating
odds are concatenating
evens are concatenating
odds are concatenating
As binary: 00011
Process completed.
But for evens, it just repeats over and over again "evens are concatenating
odds are concatenating". Hmmmm . . . whats broken in my logic?
edit: I changed the decimal in my loop from a float to an int, and it no longer hangs on evens. (what was happening the float with its huge amount was divising crazy small numbers as it went down) Now its giving me wrong numbers in answer to my even input. 4 came out as what 2 should have been.
Last edited by dchw_dude : February 21st, 2008 at 11:39 PM.
|
| |