我是新的Python,我正在练习一些东西,但我似乎无法解决为什么我的代码中显示的下面4个等级不能正确地除以4.例如,我将所有等级输入为2并显示为6.5作为总成绩平均值。
下面是代码:
#FinalGrade
Student = str(input("Student Name: "))
Grade1 = int(input("Enter Student's First Grade: "))
Grade2 = int(input("Enter Student's Second Grade: "))
Grade3 = int(input("Enter Student's Third Grade: "))
Grade4 = int(input("Enter Student's Fourth Grade: "))
print ("Total Grade Average: %G" % (Grade1+Grade2+Grade3+Grade4/4))
print ("%s has:" % (Student))
if Grade1+Grade2+Grade3+Grade4/4 < 40:
print ("Failed!")
if Grade1+Grade2+Grade3+Grade4/4 > 40:
print ("Passed!")
答案 0 :(得分:3)
更改
Grade1+Grade2+Grade3+Grade4/4
到
(Grade1+Grade2+Grade3+Grade4)/4
在此处查看不同之处:
>>> 1 + 2 +3 +4/4
7
>>> (1+2+3+4)/4
2
>>>
在第一种情况下,该值被评估为
Grade1+Grade2+Grade3+(Grade4/4)
你想要的是
(Grade1+Grade2+Grade3+Grade4)/4
考虑将其提取为局部变量。
#FinalGrade
Student = str(input("Student Name: "))
Grade1 = int(input("Enter Student's First Grade: "))
Grade2 = int(input("Enter Student's Second Grade: "))
Grade3 = int(input("Enter Student's Third Grade: "))
Grade4 = int(input("Enter Student's Fourth Grade: "))
average = (Grade1+Grade2+Grade3+Grade4 )/4
print ("Total Grade Average: %G" % (average))
print ("%s has:" % (Student))
if average < 40:
print ("Failed!")
if average > 40:
print ("Passed!")
#what if average == 40 ?
要在同一行输入所有内容,
passed_or_failed = "Passed"
if average < 40:
passed_or_failed = 'Failed'
print ("%s has: %s" % (Student, passed_or_failed))
答案 1 :(得分:3)
这不是python。您需要了解数学运算符的优先级规则。
你只将Grade4除以4,而不是等级的总和。
答案 2 :(得分:1)
由于order of operations,实际评估的是
Grade1 + Grade2 + Grade3 + (Grade4 / 4)
要解决此问题,请在成绩周围使用括号或单独求和:
gradeAvg = (Grade1 + Grade2 + Grade3 + Grade4) / 4
gradeSum = Grade1 + Grade2 + Grade3 + Grade4
gradeAvg = gradeSum / 4
答案 3 :(得分:1)
if (Grade1+Grade2+Grade3+Grade4)/4 < 40: