以下代码从用户那里获得了他上学期所学课程的某些成绩及其权重。用户完成操作后,他将输入“完成”而不是成绩。 我需要完成一个计算加权平均值的代码,并将其存储在四舍五入到百分之一的变量res中。
weighted average = sum(grade*points)/sum(points)
这是我到目前为止尝试过的:
grade = input("enter your grade: ")
points = input("enter the points: ")
#innitialise the variables before while loop:
sum_grade = 0
sum_points = 0
#write a while loop that terminates when the user enters "done" to grade variable
#calculate the grade to variable res in this format XX.XX
while grade != "done":
sum_grade += int(grade)
sum_points += int(points)
grade = input("enter your grade: ")
points = input("enter the points: ")
continue
else:
break
res = sum_grade*sum_points / sum_points
res ="%.2f"%float
非常感谢您:-)
答案 0 :(得分:2)
您拥有正确的作品。您只需要按正确的顺序放置它们即可。
尝试以下代码:
sum_grade = 0
sum_points = 0
while True:
grade = input("enter your grade: ")
if grade == "done": break # done
points = int(input("enter the points: "))
grade = int(grade)
sum_grade += grade * points
sum_points += points
res = sum_grade / sum_points
res ="%.2f"%res
print(res)
输出
enter your grade: 10
enter the points: 10
enter your grade: 50
enter the points: 1
enter your grade: done
13.64
答案 1 :(得分:1)
您可以按以下方式使用Numpy
:
import numpy as np
np.average(sum_grade, axis=1, weights=sum_points)
或通过如下方式修改代码:
sum_grade += int(grade*points)
和
res = sum_grade / sum_points