gpt4 book ai didi

arrays - 如何在 Ruby 中重新创建(每次创建新的)数组?

转载 作者:数据小太阳 更新时间:2023-10-29 09:02:14 26 4
gpt4 key购买 nike

我缺少为每对数字创建新数组然后放入每对数字之和的内容吗?顺便说一句,是否可以在一行中通过“,”输入一对数字?

arr = []
sum = 0

puts "How much pair of numbers do you want to sum?"
iter = gets.to_i

iter.times do |n|
puts "Enter pair of numbers: "
a = gets.to_i
b = gets.to_i
arr << a
arr << b
end

iter.times do |n|
puts "Here are the sums: "
arr.each { |x| sum += x }
puts sum
end

输入必须是这样的:

2 # Number of pairs 
562 -881 # First pair
310 -385 # Second pair

所以输出将是:

-319
-75

最佳答案

对于问题的第一部分,您修改代码如下:

arr = []
sum = 0

puts "How much pair of numbers do you want to sum?"
iter = gets.to_i

iter.times do |n|
puts "Enter pair of numbers: "
a = gets.to_i
b = gets.to_i
arr << [a, b] # store a new 2-element array to arr
end

iter.times do |n|
puts "Here are the sums: "
arr.each { |a, b| puts a + b } # calculate and output for each
end

对于问题的第二部分,您可以:

  a, b = gets.split(',').map(&:to_i)

然后像这样重做计算/输出部分(只有一个循环):

puts "Here are the sums: "
arr.each { |a, b| puts a + b } # calculate and output for each

加上一些错误处理。

关于arrays - 如何在 Ruby 中重新创建(每次创建新的)数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32716100/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com