首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么模产生浮点数?

为什么模产生浮点数?
EN

Stack Overflow用户
提问于 2017-09-12 05:06:42
回答 1查看 37关注 0票数 0

我编写了一些代码,它以10为基数,并将其转换为不同的基数。while循环的第一次迭代生成一个整数。所有后续的迭代都会产生浮点数。为什么?它正在产生正确的答案,但作为浮点。知道为什么吗?

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-09-12 05:14:04

X // y(泛指)商x和y

这是因为num = num / abase除法操作符。将其改为:num = num // abase

更新代码:

代码语言:javascript
复制
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()

输出:

代码语言:javascript
复制
[0, 0, 0, 0, 0, 0, 0, 1]
10000000

参考资料:

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46168299

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档