Python 2-除数10每次都会返回0

时间:2019-05-08 17:20:29

标签: python-2.7

程序将两个用户输入的数字相除,然后乘以该数字,则程序每次都会返回0

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

预期输出

if (1/2) * 10 = 5, but will output 0

2 个答案:

答案 0 :(得分:0)

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

#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)

在Python 2中只得到0的原因是,如果给出整数,则只会得到整数除法。如果要进行浮点除法,则需要确保某处有小数点,以便Python知道不必将值截断为int

#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

答案 1 :(得分:0)

这是因为python需要您了解它已被浮点数除法:您可以在分隔符的末尾添加.0或键入10 / float(2)

相关问题