我一生都无法弄清楚为什么在此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

最佳答案

由于两个数字都是整数,ruby进行整数除法,因此忽略了剩余的分数,我想您所有的除法都返回0到1之间的数字,因此答案始终为0,以避免两个数字之一都应为a浮动,就像@mtm建议的那样,在两个数字之一中添加一个to_f函数

09-10 14:41