2016-11-16 142 views
-3

我给出了以下问题,并要求使用python为它编写解决方案算法。用我的代码遇到一些逻辑错误

问题: 编写一个Python程序来确定平均得分最高的学生。每个学生都需要一个中期和一个决赛。等级应该在0到100之间进行验证。输入每个学生的姓名和成绩,并计算学生的平均成绩。输出具有最佳平均值和平均值的学生姓名。

这里是我的代码:

def midTerm(): 
    midtermScore = int(input("What is the midterm Score: ")) 
    while (midtermScore <= 0 or midtermScore >= 100): 
     midtermScore = int(input("Please enter a number between 0 and 100: ")) 
    return midtermScore 
def final(): 
    finalScore = int(input("What is the final Score: ")) 
    while (finalScore < 0 or finalScore > 100): 
     finalScore = int(input("Please enter a number between 0 and 100: ")) 
    return finalScore 

total = 0 
highest = 0 
numStudents = int (input("How Many Students are there? ")) 
while numStudents < 0 or numStudents > 100: 
    numStudents = int (input("Please enter a number between 0 and 100? ")) 
for i in range (1, numStudents+1): 
    students = (input("Enter Student's Name Please: ")) 
    score = (midTerm()+ final()) 
    total += score 
avg = total/numStudents 
if (highest < avg): 
    highest = avg 
    winner = students 
print ("The Student with the higgest average is: ", winner, "With the highest average of: ", avg) 

我遇到的问题是最后一部分。该程序不会打印出平均值最高的人的姓名,而是最后输入的人的姓名。我对如何从这里前进感到困惑。你能帮忙吗?预先感谢您的帮助。

+2

看看下面这行:'students =(input(“Enter Student's Name Please:”))' - 你每次都通过循环重新分配它。 'numStudents'也具有相同的分配问题。这对于学习[debug python](https://pymotw.com/2/pdb/)来说也是一个很好的时间,因为从一眼就可以看出有多个逻辑错误,最终会给你提供不正确的结果。 – birryree

+1

你指定'赢家=学生',所以看看学生的价值,它被分配'学生=(输入(“输入学生姓名请:”))''你从来没有真正分配正确的学生导致逻辑错误。 – kyle

+0

这里可能有一个很好的问题,但你的问题标题是不恰当的。请查看http://stackoverflow.com/help/how-to-ask。 –

回答

1

你并不遥远。看看这里:

for i in range (1, numStudents+1): 
    students = (input("Enter Student's Name Please: ")) 
    score = (midTerm()+ final()) 
    total += score 
avg = total/numStudents 
if (highest < avg): 
    highest = avg 
    winner = students 

除了缩进错误(希望只是笨拙的复制粘贴)你不是实际计算每个学生的平均成绩的任何地方。试试这样的:

for i in range (numStudents): 
    student_name = (input("Enter Student's Name Please: ")) 
    student_avg = (midTerm() + final())/2 # 2 scores, summed and divided by 2 is their average score 
    if (highest < student_avg): 
     highest = student_avg 
     winner = student_name # save student name for later 

print ("The Student with the higgest average is: ", winner, "With the highest average of: ", highest) 

它看起来像你最初试图计算总的班级平均,这是不是问题陈述所描述的。希望这可以帮助!

+0

非常感谢您花时间帮助解决问题。在发布之前,我尽力自己回答这个问题,但我在这里没有选择。当然,我是一个python noob,我仍然在学习。你的回答比上面的一些评论要好得多(实际上上面的评论不鼓励人们提问)。再次感谢! – Doug

+1

可以肯定的是,我认为热心的投票是有点苛刻,但是SO确实有坚持的标准。我们都是新手一次,国际海事组织一个模糊标题的体面的问题仍然是一个体面的问题。无论如何,欢迎来到SO! – Will