当程序将两个用户输入的数字相除,然后将其相乘时,程序每次都返回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
发布于 2019-05-09 01:28:16
如果您使用的是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)
在Python2中只得到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
发布于 2019-05-09 16:43:54
这是因为python需要你让它理解你除以一个浮点数:你可以在除数结尾处添加.0或者输入10/float(2)
https://stackoverflow.com/questions/56046011
复制相似问题