【发布时间】:2017-06-27 23:20:04
【问题描述】:
我正在尝试从用户那里收集输入,将该输入作为整数存储在一个数组中,然后迭代 每隔一个数字,从第二个到最后一个,然后取这些数字并将它们乘以 2。之后,我将产品的各个数字相加,但我无法将该数学结果存储为整数
这是我的代码:
# Prompt user for input
print "Number: "
array = []
card = gets.to_i
array << card
# Prompt the user until the number is valid
until card.is_a?(Integer) && card.positive? && card.to_s.length > 10
print "Retry: "
card = gets.to_i
array << card
end
array = array.to_s.scan(/\d/).map(&:to_i) # split number in array by digit
i = -2 # starting the loop at second to last digit
t = ((array.length)/2).ceil # number of times to iterate through the array length & roundup
$sum = 0
t.times do #go through the array as many times as digits needed, starting 2nd to last
$sum += ((array[i]) * 2).digits
i -= 2
end
puts $sum
这给了我控制台错误:
Array can't be coerced into Integer (TypeError)
我还尝试获取产品的各个数字并将它们放入这样的新数组中
final_array = []
t.times do #go through the array as many times as digits needed, starting 2nd to last
final_array << ((array[i]) * 2).digits.to_i
i -= 2
end
但这给了我错误undefined method to_i for [2]:Array
我知道还有另一种方法可以使用 % 来解决此问题,但我正在尝试使用数组来解决此问题。希望有人能帮忙!
【问题讨论】:
-
试试这个:
final_array += ((array[i]) * 2).digits -
@OthmaneElKesri 非常感谢,成功了