如果我有这个数组,这只是我脑海中想到的一个随机场景:
[3,2,5,6,7,8,9,1,2]
这个字符串:
'325678912'
我将使用 Ruby 编写什么代码,它会产生以下代码:
3*2*5 = 30, 6*7*8 = 336, and 9*1*2 = 18
并将其放入一个数组中:
[30,336,18]
抱歉,我忘了输入返回错误答案的代码:
b = [3,2,5,6,7,8,9,1,2]
first = 0
third = first + 2
array = []
while first<b.length
prod=1
b[first..third].each do |x|
prod*=x.to_i
array<<prod
end
first+=2
third = first + 2
end
print array
还有我的另一段字符串代码:
a = '325678912'
number = a.split('')
first = 0
third = first + 2
array = []
while first<number.length
prod=1
number[first..third].each do |x|
prod*=x.to_i
array<<prod
end
first+=2
third = first + 2
end
print array
对于这两段代码,我得到了这个答案:[3,6,30,5,30,210,7,56,504,9,9,18,2],我想要的是:[30,336,18]
谁能告诉我我的代码有什么问题?
先感谢您!