我正在尝试创建一个用于从学生记录中计算 GPA 的程序。输入学生的姓氏和名字后,出现以下错误:
Please provide the last name of the desired student:
Cirello
Please provide the first name of the desired student:
Brian
proj3.rb:55:in `+': String can't be coerced into Fixnum (TypeError)
from proj3.rb:55:in `block in <main>'
from proj3.rb:53:in `each'
from proj3.rb:53:in `<main>'
请帮我解决这个问题。这是我的代码:
stud_id = []
last_name = []
first_name = []
course_number = []
course_name = []
prof_name = []
credit_hours = []
grade = []
grade_values = {
"A" => 4,
"B" => 3,
"C" => 2,
"D" => 1,
"F" => 0 }
fin = File.open("student-records.txt", "r")
while line = fin.gets
fields = line.chomp.split(',')
stud_id << fields[0]
last_name << fields[1]
first_name << fields[2]
course_number << fields[3]
course_name << fields[4]
prof_name << fields[5]
credit_hours << fields[6]
grade << fields[7]
end
fin.close
puts "Please provide the last name of the desired student:"
desired_last_name = gets.chomp
puts "Please provide the first name of the desired student:"
desired_first_name = gets.chomp
desired_student_credit_hours = 0
desired_student_grades = 0
desired_student_indexes = [7]
if last_name.include?(desired_last_name) && first_name.include?(desired_first_name)
last_name.each do |student_last_name, i|
if student_last_name == desired_last_name
desired_student_indexes << i
end
end
end
desired_student_indexes.each do |desired_student_index|
desired_student_grades += grade_values[grade[desired_student_index]]
desired_student_credit_hours += credit_hours[desired_student_index]
end
final_gpa = desired_student_grades / desired_student_credit_hours
puts "This student's final GPA is: #{final_gpa}"