计算学生GPA,更新总学分和总分

时间:2013-11-04 19:48:13

标签: ruby

我的部分代码需要帮助。我正在使用文本文件来获取信息并计算学生gpa。我不确定如何在代码末尾更新total_credit_hours和total_grade_points。任何帮助将不胜感激!

    total_credit_hours = 0.0

    total_grade_points = 0.0

    puts "Enter student last name: "
         desired_last_name = STDIN.gets.chomp

    puts "Enter student first name: "
         desired_first_name = STDIN.gets.chomp

    fin = File.open("studentgpa.txt", "r")
    while line = fin.gets
        fields = line.chomp.split(",")
        last_name = fields[1]
        first_name = fields[2]
credit_hours = fields[6].to_i
grade = fields[7]
if last_name == desired_last_name && first_name == desired_first_name
    if grade == "A"
        grade_points = credit_hours * 4
    elsif grade == "B"
        grade_points = credit_hours * 3
    elsif grade == "C"
        grade_points = credit_hours * 2
    elsif grade == "D"
        grade_points = credit_hours * 1
    elsif grade == "F"
        grade_points = creidt_hours * 0
        end

            total_credit_hours = 
            total_grade_points = 
        end
    end

    fin.close

    top = total_grade_points
    bottom = total_credit_hours
    m = top/bottom

    print "The desired student's grade point average is ", m,"\n"

2 个答案:

答案 0 :(得分:0)

简单

total_credit_hours = 0
total_credit_hours = credit_hours + total_credit_hours

total_grade_points = 0
total_grade_points = grade_points + total_grade_points

答案 1 :(得分:0)

@ Dejan的回答是正确的,尽管这是一种更为Ruby的方式:

total_credit_hours = 0.0
total_grade_points = 0.0

puts "Enter student last name: "
desired_last_name = STDIN.gets.chomp

puts "Enter student first name: "
desired_first_name = STDIN.gets.chomp

file = File.open("studentgpa.txt", "r")
file.read.each_line do |line|
    fields = line.chomp.split(",")
    last_name = fields[1]
    first_name = fields[2]
    credit_hours = fields[6].to_i
    grade = fields[7]
    if last_name == desired_last_name && first_name == desired_first_name
        grade_points = case grade
        when "A" then credit_hours * 4
        when "B" then credit_hours * 3
        when "C" then credit_hours * 2
        when "D" then credit_hours * 1
        when "F" then credit_hours * 0
        end

        total_credit_hours += credit_hours
        total_grade_points += grade_points
    end
end
file.close

gpa = total_grade_points/total_credit_hours
puts "The desired student's grade point average is #{gpa}"