请用for函数做程序:从键盘输入十个学生的成绩,统计最高分,最低分和平均分。 max代表最高分,min代表最低分,avg代表平均分。
时间: 2024-02-23 18:00:06 浏览: 33
好的,以下是使用for循环的程序:
```python
def main():
print('请分别输入十个学生的成绩:')
a = []
for i in range(10):
a.append(float(input("请输入第%d个学生的成绩,并按回车继续:" % (i + 1))))
max_score = a[0] # 最高分初始化为第一个学生的成绩
min_score = a[0] # 最低分初始化为第一个学生的成绩
total_score = 0 # 总成绩初始化为0
for score in a:
if score > max_score:
max_score = score
if score < min_score:
min_score = score
total_score += score
avg_score = total_score / 10 # 平均分计算
print("max:{}\nmin:{}\navg:{}\n".format(max_score, min_score, avg_score))
if __name__ == '__main__':
main()
```
在循环中,我们遍历了输入的学生成绩列表,通过if语句判断每位学生的成绩是否是最高分或最低分,并累加每位学生的成绩,最后计算平均分。
相关问题
写一个程序 在键盘上输入10个学生的成绩 统计最高分 最低分 和平均分
好的,这是一个基于 Python 语言的程序,可以实现你的需求:
```python
scores = []
for i in range(10):
score = int(input("请输入第%d个学生的成绩:" % (i+1)))
scores.append(score)
max_score = max(scores)
min_score = min(scores)
avg_score = sum(scores) / len(scores)
print("最高分为:", max_score)
print("最低分为:", min_score)
print("平均分为:", avg_score)
```
程序的实现很简单,首先定义一个空列表 scores,然后使用 for 循环输入 10 个学生的成绩,将成绩添加到 scores 列表中。接着使用内置函数 max、min 和 sum 计算最高分、最低分和平均分,最后输出结果即可。
以defmain开头,从键盘输入十个学生的成绩统计最高分最低分和平均分max代表最高分命代表最低分艾瑞者代表平均分请改正程序中的错误使它能得出正确的结果
以下是已经修改好的代码:
```python
def main():
scores = []
for i in range(10):
score = float(input("请输入第{}个学生的成绩:".format(i+1)))
scores.append(score)
max_score = max(scores)
min_score = min(scores)
avg_score = sum(scores)/len(scores)
print("最高分:{:.2f}".format(max_score))
print("最低分:{:.2f}".format(min_score))
print("平均分:{:.2f}".format(avg_score))
if __name__ == '__main__':
main()
```
主要修改了以下几点:
1. 函数名应该是 `main` 而非 `defmain`。
2. 输入的成绩需要转换为浮点数类型。
3. 计算平均分时应该使用 `sum(scores)/len(scores)`。
4. 输出结果时保留两位小数,使用 `{:.2f}` 格式化字符串。