Computer Science Canada

why doesnt this binary converter work?

Author:  limited_skillz [ Sat Apr 17, 2004 6:06 pm ]
Post subject:  why doesnt this binary converter work?

code:
var userNumber, base : int
put "Enter number: " ..
get userNumber
var tempWord : string := ""
base := 2
loop
    tempWord := tempWord + intstr (userNumber mod base)
    userNumber div= base
    exit when userNumber = 1
end loop
put "Number in Binary: "..
for decreasing i : length (tempWord) .. 1
    put tempWord (i) ..
end for


with all this conversion talk i wanted to try it out for myself

why doesnt this program give the right answer? is it because of integer overflow or something?

Author:  Tony [ Sat Apr 17, 2004 6:19 pm ]
Post subject: 

you don't divide userNumber by base in the loop, you subtract userNumber mod base from it

Author:  limited_skillz [ Sun Apr 18, 2004 12:13 am ]
Post subject: 

code:
var userNumber, base : int
put "Enter number: " ..
get userNumber
var tempWord : string := ""
base := 2
loop
    tempWord := tempWord + intstr (userNumber mod base)
    userNumber -= userNumber mod base
    exit when userNumber = 1
    put tempWord
    delay (10)
end loop
put "Number in Binary: "..
for decreasing i : length (tempWord) .. 1
    put tempWord (i) ..
end for


still doesnt work, in fact it just goes on forever like this Sad til an error occurs

Author:  Tony [ Sun Apr 18, 2004 11:54 am ]
Post subject: 

umm... yeah... maybe I should try to actually read all of the code instead of looking at random lines Embarassed

anyways,
code:

var num, base:int
put "enter number:"..
get num
base := 2
put ""
put intstr(num,0,base)

Laughing

Author:  EDEN-E [ Sun Apr 18, 2004 12:12 pm ]
Post subject:  Re: why doesnt this binary converter work?

you first code was right except one line.


When program divide 1 by 2 (which will be the last process),

the userNumber will be 0.5

However, because userNumber variable is int type, userNumber will be 0.

so loop have to be exit when userNumber = 0

Author:  Flashkicks [ Tue Apr 20, 2004 7:51 am ]
Post subject: 

There is a Very handy MegaConverter just at the top of the Turing Help room. You should reallycheck it out. It is extremely short and efficent and does ALL the convertersions.. [fyi: it uses instr and wutnot- it is the short method... the kind the teachers dont really like Rolling Eyes ]


: