首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python 2-除法乘以10每次返回0

Python 2-除法乘以10每次返回0
EN

Stack Overflow用户
提问于 2019-05-09 01:20:29
回答 2查看 27关注 0票数 1

当程序将两个用户输入的数字相除,然后将其相乘时,程序每次都返回0

代码语言:javascript
复制
correct = input("User, Input the amount of correct answers. :")
points_possible = input("User, Input the amount of points possible. :")

score = correct / points_possible
grade = score * 10

print grade

预期输出

代码语言:javascript
复制
if (1/2) * 10 = 5, but will output 0
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-05-09 01:28:16

如果您使用的是Python 2.7版本,则从控制台获取的输入将始终采用字符串的形式。因此,您需要将其转换为整数。

代码语言:javascript
复制
#code in Python 3.5
correct = int(input("User, Input the amount of correct answers. :"))
points_possible = int(input("User, Input the amount of points possible. :"))

score = correct / points_possible
grade = score * 10

print(grade)

在Python2中只得到0的原因是,如果给定了整数,那么只会得到整数除法。如果你想要浮点式除法,你需要确保在某个地方有一个小数点,这样Python就知道它不必将值截断为int

代码语言:javascript
复制
#code in Python 2.7
correct = float(raw_input("User, Input the amount of correct answers. :"))
points_possible = float(raw_input("User, Input the amount of points possible. :"))

score = correct / points_possible
grade = score * 10.0

print grade
票数 0
EN

Stack Overflow用户

发布于 2019-05-09 16:43:54

这是因为python需要你让它理解你除以一个浮点数:你可以在除数结尾处添加.0或者输入10/float(2)

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

https://stackoverflow.com/questions/56046011

复制
相关文章

相似问题

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