【发布时间】:2021-01-06 08:18:54
【问题描述】:
我正在尝试创建一个方法,该方法遍历一个数组并将其所有元素相加并返回为其总和一半的元素,否则它将返回 nil。
例子:
p all_else_equal([2, 4, 3, 10, 1]) #=> 10, because the sum of all elements is 20
p all_else_equal([6, 3, 5, -9, 1]) #=> 3, because the sum of all elements is 6
p all_else_equal([1, 2, 3, 4]) #=> nil, because the sum of all elements is 10 and there is no 5 in the array.
我的解决方案是遍历数组并使用“sum”变量将每个元素相加。然后编写一个条件语句,说明如果总和的一半包含在 arr 中,则返回元素,否则返回 nil。但是对于任何重新赛季,我一直得到“零”。有谁能告诉我为什么这是错误的?这是我的代码:
def all_else_equal(arr)
sum = 0
sum_half = sum / 2
arr.each_with_index do |ele, i|
sum += ele
if sum_half == ele
return ele
else
return nil
end
end
end
控制台:
nil
【问题讨论】: