我正在尝试执行一个程序,一次向用户询问三个数字,将它们存储在数组中,然后打印数字列表和总数。
请解释。
这是我到目前为止所做的:
numbers = Array.new
numbers = []
puts "Enter first number: "
first = gets.to_i
puts "Enter second number: "
second = gets.to_i
puts "Enter third number: "
third = gets.to_i
def sum(numbers)
return 0 if numbers.length < 1
result = 0
numbers.each { |num| result += num }
result
end
答案 0 :(得分:2)
您也可以使用Array的reduce方法。
http://ruby-doc.org/core-2.1.0/Enumerable.html#method-i-reduce
#!/usr/bin/ruby
numbers = Array.new
# numbers = [] #this is same as above
puts "Enter first number: "
first = gets.to_i
numbers<<first
puts "Enter second number: "
second = gets.to_i
numbers<<second
puts "Enter third number: "
third = gets.to_i
numbers<<third
puts numbers.reduce {|sum, n| sum + n } #here
答案 1 :(得分:2)
这是另外一种方法:
long minutes = TimeUnit.MILLISECONDS.toMinutes(a - b);
也可以写成如下:
sum = 3.times.collect{ |i| puts "Enter number #{i + 1}:"; gets.chomp.to_i }.inject(:+)
puts sum
答案 2 :(得分:0)
您没有将任何输入推入阵列,您可以使用推送功能或&lt;&lt;向元素中添加元素
#!/usr/bin/ruby
numbers = Array.new
numbers = []
puts "Enter first number: "
first = gets.to_i
numbers<<first
puts "Enter second number: "
second = gets.to_i
numbers<<second
puts "Enter third number: "
third = gets.to_i
numbers<<first
def sum(someArray)
return 0 if someArray.length < 1
result = 0
someArray.each { |num| result += num }
result
end
希望有所帮助
答案 3 :(得分:0)
这里有两个问题:
sum
功能,但未在任何地方调用
#!/usr/bin/ruby
numbers = Array.new # note the second, redundant, initialization on numbers was removed
puts "Enter first number: "
(numbers ||= []) << gets.to_i # Pushing read value into the array (issue 1)
puts "Enter second number: "
(numbers ||= []) << gets.to_i # Here too
puts "Enter third number: "
(numbers ||= []) << gets.to_i # And here too
def sum(numbers)
return 0 if numbers.length < 1
result = 0
numbers.each { |num| result += num }
result
end
puts sum(numbers) # Calling sum (issue 2)