python - Why is modulo resulting in floating point numbers? -
i wrote code takes 10 base number , converts different base number. first iteration of while loop produces integer. subsequent iterations produce floating point numbers. why? producing correct answer, floating point. idea why?
num = 128 abase = 2 tlist = [] while num > 0: tcr = num%abase tlist.append(tcr) num -= tcr num = num / abase print(tlist) tlist = tlist[::-1] temp = 0 item in tlist: temp *= 10 temp += item temp = str(temp) print(temp)
x // y (floored) quotient of x , y
it because of num = num / abase
division operator. change to: num = num // abase
updated code:
def test(): num = 128 abase = 2 tlist = [] while num > 0: tcr = num%abase tlist.append(tcr) num -= tcr num = num // abase print(tlist) tlist = tlist[::-1] temp = 0 item in tlist: temp *= 10 temp += item temp = str(temp) print(temp) test()
output:
[0, 0, 0, 0, 0, 0, 0, 1] 10000000
reference:
Comments
Post a Comment