在数组中添加奇数不提供正确的输出

时间:2016-09-21 23:13:01

标签: arrays ruby

我的一个ruby程序检测到数组中的奇数并将它们加在一起并不能提供正确的输出。鉴于我正在学习ruby并且这是一个逻辑错误,我不能轻易地扣除我犯错误的地方。 这是代码:

Master

问题:为什么输出错误?有什么办法让这个更清洁或更好? 我在cloud9上的一个名为oddball.rb的程序中运行了所有这些。

3 个答案:

答案 0 :(得分:2)

return result会导致代码在那时退出......它只会累加第一个数字,然后永远退出整个方法......它永远不会看到其他元素阵列。

现在已正确缩进代码,您可以看到此行在while循环中... 可能你希望它在while循环之外...当你正确地缩进你的代码时,更容易看到这种错误。你应该总是缩进你的代码......在你遇到这样的bug之前它似乎并不重要......它总是很重要。从现在开始这是一个好习惯。 ;)

答案 1 :(得分:1)

查看你的if语句:结果+ = 1,不要添加1但是添加你当前正在测试的数字:结果+ =数字[索引]

的SiS

答案 2 :(得分:1)

def odd_sum(numbers)
  index = 0
  result = 0 
  while index < numbers.length
    if (numbers[index] % 2 != 0)
      result += 1
    end
    index +=1
    return result
  end
end  

puts odd_sum([1,2,4,5,7,9]) currently my output is 1 should be 22
puts odd_sum([0,6,4,4]) currently output 0
puts odd_sum([1,2,1]) currently output 1 should be 2

result += 1行上,每次有奇数时都会添加1,因此它不是总和,而是计数。

return result行上,程序会在点击return时立即结束。因此,由于第一个数组中的第一个数字是奇数,程序将结果增加1,然后返回结果。

您要做的是result += numbers[index],并在while循环结束时返回结果。

在Ruby中,通常有更好的方法来处理事情,而循环则意味着当你不知道循环的次数时。在这种情况下,你确切地知道了多少次,所以我建议使用迭代器。

def odd_sum(numbers)
  result = 0
  numbers.each do |num|
    result += num if num.odd?
  end
end

甚至更好

def odd_sum(numbers)
  numbers.select(&:odd?).reduce(&:+)
end
相关问题