我已经为代码战编写了一个程序,该程序查找最低的两个整数并返回它们的和:
def sum_two_smallest_numbers(numbers)
array_lowest = [0, 0]
main_iterate = 2
array_lowest[0] = sum_two_smallest_numbers[0]
array_lowest[1] = sum_two_smallest_numbers[1]
until main_iterate == sum_two_smallest_numbers.length - 1 #maybe -2, or 0
if sum_two_smallest_numbers[main_iterate] < array_lowest[0]
array_lowest[0] = sum_two_smallest_numbers[main_iterate]
main_iterate += 1
elsif sum_two_smallest_numbers[main_iterate] < array_lowest[1]
array_lowest[1] = sum_two_smallest_numbers[main_iterate]
main_iterate += 1
else
main_iterate += 1
end
end
return array_lowest[0] + array_lowest[1]
end
完成以下测试:
Test.assert_equals(sum_two_smallest_numbers([5, 8, 12, 18, 22]), 13)
Test.assert_equals(sum_two_smallest_numbers([7, 15, 12, 18, 22]), 19)
Test.assert_equals(sum_two_smallest_numbers([25, 42, 12, 18, 22]), 30)
它抱怨我的第一行(这是与end
一起提供的),并且如果我将numbers
替换为任何实际数字(如在测试用例中一样),则会抛出此错误:
syntax error, unexpected tINTEGER, expecting ')'
我该如何解决?
答案 0 :(得分:1)
您正在递归调用sum_two_smallest_numbers
,但不带参数。它需要一个参数。每次编写sum_two_smallest_numbers
时,这就是方法调用。当您编写sum_two_smallest_numbers[0]
时,这是一个没有参数的方法调用,如果调用成功,则[0]
将访问返回值的第0个元素。
似乎您可能想要numbers[0]
,sum_two_smallest_numbers[0]
。