gpt4 book ai didi

ruby - 当我运行它时,sum+=n 语句中有问题,我不知道如何修复它

转载 作者:太空宇宙 更新时间:2023-11-03 17:48:28 25 4
gpt4 key购买 nike

class Test
def multiples
(1..1000).each do |n|
if n % 3 == 0 || n % 5 == 0
sum += n
end
puts "The sum of multiples of 3 or 5 below 1000 is #{sum}"
end
end
end
test = Test.new
test.multiples

错误:

test.rb:9:in `block in multiples': undefined method `+' for nil:NilClass (NoMethodError)
The sum of multiples of 3 or 5 below 1000 is
from test.rb:7:in `each'
from test.rb:7:in `multiples'
from test.rb:19:in `<top (required)>'
from -e:1:in `load'
from -e:1:in `<main>'

最佳答案

你还没有初始化 sum,添加 sum = 0 应该可以解决这个问题:

class Test
def multiples
sum = 0
(1..1000).each do |n|
if n % 3 == 0 || n % 5 == 0
sum += n
end
puts "The sum of multiples of 3 or 5 below 1000 is #{sum}"
end
end
end
test = Test.new
test.multiples

关于ruby - 当我运行它时,sum+=n 语句中有问题,我不知道如何修复它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29776051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com