Reputation: 41
I wrote some code that takes a 10 base number and converts it to a different base number. The first iteration of the while loop produces an integer. All subsequent iterations produce floating point numbers. Why? It is producing the correct answer, but as floating point. Any 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
for item in tlist:
temp *= 10
temp += item
temp = str(temp)
print(temp)
Upvotes: 0
Views: 46
Reputation: 13651
x // y (floored) quotient of x and y
It is because of the num = num / abase
division operator. Change it 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
for item in tlist:
temp *= 10
temp += item
temp = str(temp)
print(temp)
test()
Output:
[0, 0, 0, 0, 0, 0, 0, 1]
10000000
Reference:
Upvotes: 3