If we list all natural numbers less than 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all numbers less than 1000, multiples of 3 or 5.
I just started learning Ruby, I used to work only with C languages. Please explain why this code doesn't work. Thank you!!!
代碼:
sum = 0;
i = 3;
while (i < 1000) do
if ((i % 3 == 0) || (i % 5 == 0))
sum = i;
end
end
puts "The sum of all the multiples of 3 or 5 below 1000: #{sum}"
當我運行檔案時,它會無限期地加載。 在此處輸入影像描述
uj5u.com熱心網友回復:
你永遠不會增加 i。
while 回圈將在以下情況下終止: i >= 1000
但是 i = 3 并且沒有 i =1,因此此回圈將永遠不會終止。
uj5u.com熱心網友回復:
(0..1000).filter { |i| i % 3 == 0 || i % 5 == 0 }.sum
如果你像另一個答案中所說的那樣增加 i ,你的方法很好,但是更慣用的 Ruby 看起來像這樣。
uj5u.com熱心網友回復:
(0..10000).select(&->(i){ (i % 3).zero? || (i % 5).zero? }).sum
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/474199.html
標籤:红宝石
