如何在Python中计算百分比

17 投票
10 回答
193499 浏览
提问于 2025-04-17 20:45

这是我的程序

print" Welcome to NLC Boys Hr. Sec. School "
a=input("\nEnter the Tamil marks :")
b=input("\nEnter the English marks :")
c=input("\nEnter the Maths marks :")
d=input("\nEnter the Science marks :")
e=input("\nEnter the Social science marks :")
tota=a+b+c+d+e
print"Total is: ", tota
per=float(tota)*(100/500)
print "Percentage is: ",per

结果

Welcome to NLC Boys Hr. Sec. School 

Enter the Tamil marks :78

Enter the English marks :98

Enter the Maths marks :56

Enter the Science marks :65

Enter the Social science marks :78 Total is:  375 Percentage is:  0.0

但是,计算出来的百分比结果是 0。我该如何在Python中正确计算百分比呢?

10 个回答

5

这是因为 (100/500) 是一个整数运算,结果是 0。

试试这个:

per = 100.0 * tota / 500

其实不需要用 float(),因为如果你用一个带小数点的数字(比如 100.0),整个运算就会变成小数运算了。

8

你正在进行一个整数除法。在数字后面加上一个.0

per=float(tota)*(100.0/500.0)

在Python 2.7中,除法100/500==0

正如@unwind所指出的,float()这个调用其实是多余的,因为用浮点数进行乘法或除法会返回一个浮点数:

per= tota*100.0 / 500
19

我猜你正在学习Python。其他的回答都是对的。不过我来回答你主要的问题:“如何在Python中计算百分比”。

虽然你现在的方法可以用,但看起来不太像Python的风格。而且,如果你需要添加一个新科目怎么办?你就得再加一个变量,使用另一个输入等等。我想你是想计算所有分数的平均值,所以每次添加新科目时,你还得修改科目的数量!这看起来真麻烦……

我给你提供一段代码,你只需要在一个列表中添加新科目的名字就可以了。如果你能理解这段简单的代码,你的Python编程技能会有一点提升。

#!/usr/local/bin/python2.7

marks = {} #a dictionary, it's a list of (key : value) pairs (eg. "Maths" : 34)
subjects = ["Tamil","English","Maths","Science","Social"] # this is a list

#here we populate the dictionary with the marks for every subject
for subject in subjects:
   marks[subject] = input("Enter the " + subject + " marks: ")

#and finally the calculation of the total and the average
total = sum(marks.itervalues())
average = float(total) / len(marks)

print ("The total is " + str(total) + " and the average is " + str(average))

在这里你可以测试这段代码并进行实验。

撰写回答