我应该如何解决此错误?我对ruby变量有问题



程序

该程序应该接受输入,将其转换为浮点值,并将其计算为字母等级和数字。它应该从所有的案例中提取它,并在报表中打印出来

代码

puts "Please enter your grade:"
grade = gets.chomp.to_f
puts "Please enter the amount the assignment is being graded on:"
outof = gets.chomp.to_f
finalresult = (grade / outof)*1000
puts "Your letter grade is #{$result} and your percentage is #{finalresult}."
$result = 0.00
case finalresult 
when finalresult == 0..399
$result == "E"
when finalresult == 400..499
$result == "D"
when finalresult == 500..549
$result == "C-"
when finalresult == 550..599
$result == "C"
when finalresult == 600..649
$result == "C+"
when finalresult == 650..699
$result == "B-"
when finalresult == 700..749
$result == "B"
when finalresult == 750..799
$result == "B+"
when finalresult == 800..849
$result == "A-"
when finalresult == 850..899
$result == "A"
when finalresult == 900..1000
$result == "A+"
end

输出/错误

在此处输入图像描述

when中删除finalresult ==部分,并使用=而不是==分配$result:

case finalresult 
when 0..399
$result = "E"
when 400..499
$result = "D"
when 500..549
$result = "C-"
# ...
end

您可能还想用result替换$result,即使用局部变量而不是全局变量。

您可以考虑将case语句移动到一种方法中:

def grade(value)
case value
when 0..399 then "E"
when 400..499 then "D"
when 500..549 then "C-"
# ...
end
end

您可能希望简单地使用一个数组将数字等级与字母等级相关联:

NBR_GRADE_TO_LTR_GRADE = [
[399, "E"], [499, "D"], [549, "C-"], [550, "C"], [649, "C+"], [699, "B-"],
[749, "B"], [799, "B+"], [849, "A-"], [899, "A"], [1000, "A+"]
]
def ltr_grade(grade, outof)
p_grade = (1000 * (grade.fdiv(outof))).round
l_grade = NBR_GRADE_TO_LTR_GRADE.find { |nbr, _ltr| p_grade <= nbr }.last
[l_grade, p_grade] 
end
grade = 80
outof = 100
puts "Your letter grade is %s and your numeric grade is %d." %
ltr_grade(grade, outof)
Your letter grade is A- and your numeric grade is 800
grade = 10
outof = 100
puts "Your letter grade is %s and your numeric grade is %d." %
ltr_grade(grade, outof)
Your letter grade is E and your numeric grade is 100.

第一个示例的中间计算如下。

grade = 80
outof = 100
p_grade = (1000 * (grade.fdiv(outof))).round
#=> 800  
a = l_grade = NBR_GRADE_TO_LTR_GRADE.find { |nbr, _ltr| p_grade <= nbr }
#=> [849, "A-"]
a.last
#=> "A-" 

相关内容

最新更新