2013-05-21 33 views
1

我加入是3的倍数所有数字和5低于1000while循环小于号“<”养在红宝石(RubyMine的)错误

这是我的错误:

in `multiple_sum': undefined method `<' for nil:NilClass (NoMethodError) 

这里是我的代码:

def multiple_sum(n) 
    five_total, three_total, three_subtract = 0 
    while five_total < n 
    five_total += five_total+5 
    end 
    while three_total < n 
    if (three_total+3)%5 == 0 
     three_subtract += three_total+3 
    end 
    three_total += three_total+3 
    end 
    puts (three_total-three_subtract) + five_total 
end 

multiple_sum(1000) 

有没有跟我while循环条件有问题吗?

+0

虽然你的“bug”已经修复,但这段代码实际上并没有做你说的。如果你调用'multiple_sum(11)',它返回36,但它应该加上数字3 + 6 + 9 + 5 + 10 = 33(如果你的意思是“3的倍数和5的倍数” 0,如果你的意思是5和3的倍数),'multiple_sum(3)'返回8! ;-) – Pavling

回答

4

你可能寻找链式分配:five_total = three_total = three_subtract = 0

4

没有。你只是不列出的所有变量设定值:

five_total, three_total, three_subtract = 0 

该代码分配零到第一个变量,只有five_totalthree_totalthree_subtract设置为nil

你应该设置他们太多:

five_total, three_total, three_subtract = 0, 0, 0 
+0

哇,非常感谢你 – Logan

+0

@logan欢迎你=) – shybovycha