如何在数组中显示最大值

时间:2017-11-05 19:08:37

标签: ruby

我的以下程序应该跟踪每个输入,启动计数器,并每次显示最大输入。

<div class="ui main center aligned text container clearing segment">
</div>

但该程序最终没有显示数组中的最高输入。当我输入整数puts "Please enter an integer" count=1 a = [] while count <= 10 puts "this is the count #{count}" puts "this is the highest integer so far: #{a.max}" count = count+1 input = gets.chomp a << input end puts "this is the highest integer #{a.max}" "\n" puts a.max 1023456,{{1}时},7111300的值会重置为每个输入的输入,直到我到达7,它会重复。

1 个答案:

答案 0 :(得分:1)

您正在使用max来获取字符串数组中的最大元素。尝试将引入的值转换为整数,在迭代结束时,您将能够获得其中的最大元素:

puts 'Please enter an integer'
count = 1
a = []

while count <= 10
  puts "this is the count #{count}"
  puts "this is the highest integer so far: #{a.max}"
  count += 1
  input = gets.chomp.to_i
  a << input
end

puts "this is the highest integer #{a.max}\n"
puts a.max

或者,你可以在一个范围内使用each_with_object来指定一个初始值为0的数组,然后开始迭代,并且#34;填充&#34;数组:

puts 'Please enter an integer'

array = (0..9).each_with_object([0]) do |index, memo|
  puts "this is the count #{index}"
  puts "this is the highest integer so far: #{memo.max}"
  memo[index] = gets.chomp.to_i
end

p array.max