python
Copy code
import random
class Student:
def __init__(self, student_id, score):
self.student_id = student_id
self.score = score
# (1) 輸入學生資料
students = [Student(f"{i+1:08d}", random.randint(0, 100)) for i in range(50)]
# (2) 計算平均分數與及格人數
average_score = sum(student.score for student in students) / len(students)
passing_students_count = sum(1 for student in students if student.score >= 60)
# (3) 尋找最高分與最低分的學生
highest_scoring_student = max(students, key=lambda s: s.score)
lowest_scoring_student = min(students, key=lambda s: s.score)
# 輸出平均分數與及格人數
print(f"平均分數:{average_score:.2f}")
print(f"及格人數:{passing_students_count}")
# 輸出最高分與最低分的學生資料
print(f"最高分的學生資料:學號-{highest_scoring_student.student_id}, 分數-{highest_scoring_student.score}")
print(f"最低分的學生資料:學號-{lowest_scoring_student.student_id}, 分數-{lowest_scoring_student.score}")
# (4) 將全部學生資料輸出到檔案
with open("score.dat", "w") as file:
for student in students:
file.write(f"學號:{student.student_id}, 分數:{student.score}\n")
這段代碼首先創建了一個 Student 類來存儲每位學生的學號和分數。然後,它通過迴圈和 random.randint(0, 100) 函數為每位學生隨機生成一個分數。接著,程式計算平均分數和及格人數,並找到最高分和最低分的學生。最後,將所有學生的資料輸出到名為 score.dat 的檔案中。
請注意,這裡使用隨機生成的分數來模擬學生的分數輸入,實際應用中應該通過用戶輸入或從數據庫讀取學生資料來替代這一部分。