3

我一生都无法弄清楚为什么在这个 Aslsx 导出中除法不起作用。我可以加法、减法、乘法和模除法,但是当我尝试这样做时,answer_number / question_number它总是显示为 0。任何想法我做错了什么?

作品吐出answer_number时代question_number

@survey.questions.each do |question|
        question_number = Choice.where(question_id: question.id).length
        question.answers.each do |answer|
            answer_number = Choice.where(answer_id: answer.id).length
            sheet.add_row [answer_number, question_number, answer_number * question_number]
        end
    end

不起作用 - 吐出 0:

@survey.questions.each do |question|
        question_number = Choice.where(question_id: question.id).length
        question.answers.each do |answer|
            answer_number = Choice.where(answer_id: answer.id).length
            sheet.add_row [answer_number, question_number, answer_number / question_number]
        end
    end

我还认为,当数字小于 0 时,它可能会进行某种舍入,但这似乎也不起作用(最终目标是获得每个答案的百分比):

@survey.questions.each do |question|
        question_number = Choice.where(question_id: question.id).length
        question.answers.each do |answer|
            answer_number = Choice.where(answer_id: answer.id).length
            sheet.add_row [answer_number, question_number, answer_number / question_number * 100]
        end
    end
4

1 回答 1

6

由于两个数字都是整数,ruby 正在进行整数除法,它会忽略剩余的分数,我猜你所有的除法都返回 0 和 1 之间的数字,所以答案总是 0,以避免两个数字之一应该是像@mtm建议的那样浮动,to_f向其中一个数字添加一个函数

于 2014-09-10T14:58:19.010 回答