我需要创建一个成绩计算器,将5个测试的结果放在一起并求平均值,并给出5个成绩的结果,我制作了最终的成绩结果程序,但我不知道如何进行循环仅运行五次并对每个输入结果求和。
grade = 0
total = 0
for grade in range(0,5):
if grade >= 0 and grade <= 100:
grade = grade + int(input('What was your score: '))
elif grade >= 101:
grade += int(input('It should be a number from 0 to 100, what was your
score: '))
if 93<=grade <= 100:
print 'A'
elif 90 <= grade < 93:
print 'A-'
elif 87 <= grade < 90:
print 'B+'
elif 83 <= grade < 87:
print 'B'
elif 80 <= grade < 83:
print 'B-'
elif 77 <= grade < 80:
print 'C+'
elif 73 <= grade < 77:
print 'C'
elif 70 <= grade < 73:
print 'C-'
elif 67 <= grade < 60:
print 'D+'
elif 63 <= grade < 67:
print 'D'
elif 60 <= grade < 63:
print 'D-'
elif grade < 60:
print 'F'
您没有正确从用户输入中收集成绩,因为您还向成绩添加了增量值 (0 - 5),这会导致不正确的结果。
对于循环,您可以做的是维护正确输入的成绩数并运行它,直到达到限制(在您的情况下为 5)。
以下是对您的代码的可能修复:
total = 0
gradeCount = 0
while gradeCount < 5:
grade = int(input('What was your score: '))
if grade < 0 or grade > 100:
print('It should be a number from 0 to 100')
else:
gradeCount += 1
total += grade
if 93 <= grade <= 100:
print('A')
elif 90 <= grade < 93:
print('A-')
elif 87 <= grade < 90:
print('B+')
elif 83 <= grade < 87:
print('B')
elif 80 <= grade < 83:
print('B-')
elif 77 <= grade < 80:
print('C+')
elif 73 <= grade < 77:
print('C')
elif 70 <= grade < 73:
print('C-')
elif 67 <= grade < 60:
print('D+')
elif 63 <= grade < 67:
print('D')
elif 60 <= grade < 63:
print('D-')
elif grade < 60:
print('F')
average = total / gradeCount
print('Average: ' + str(average))
您正在向成绩添加增量值,这会给出不正确的结果
total = 0
gradeCount = 0
while gradeCount < 5:
if grade < 0 or grade > 100:
print('It should be a number from 0 to 100')
else:
gradeCount += 1
total += grade
// Your calculation here
average = total / gradeCount
print('Average: ' + str(average))
如果您想了解如何设计成绩计算器,您还可以参考以下链接。 成绩计算器