开发者

Trying to calculate percentage of a quiz score, Rails 3.0.3

开发者 https://www.devze.com 2023-02-13 09:54 出处:网络
I\'m trying to calculate a score (in percentage) based on how many of 20 questions were answered correctly, what I\'m doing is checking each answer with a answer key on the database then assigning a v

I'm trying to calculate a score (in percentage) based on how many of 20 questions were answered correctly, what I'm doing is checking each answer with a answer key on the database then assigning a variable a 1 or a 0 based on whether or not it's correct, 1 for correct 0 for incorrect. I'll give an example:

<% if result.q01 == @answer01 %>
<% @score01 = 1 %>
<% else %>
<% @score01 = 0 %>
<% end %>  

it assigns the variable correctly but when I do the math to figure out the percentage it's in correct. the math I do is (in this example I'll only add up the first 2 scored answers:

<% @grade = @score01 + @score02 %>
<% @finalgrade = @grade / 20 * 100 %>

but the final grade does not add up like when I add up on a calculator it's reporting a开发者_运维技巧 0 instead of 10 (in this case @grade adds up to be 2). Any idea why it's behaving this way? I'm stumped. Thank you!


First, you need to wrap your @grade / 20 statement in parentheses. Also, you need to convert one of those numbers to a float, otherwise you'll always get 0 as a result unless @grade is 20 (dividing one integer into another will never return anything but a whole number).

<% @finalgrade = (@grade / 20.0) * 100 %>
0

精彩评论

暂无评论...
验证码 换一张
取 消