嵌套循环红宝石答案

时间:2019-03-17 18:37:34

标签: ruby loops

在循环结束后需要协助保存和总计“降雨输入”。任何建议将不胜感激。

puts "How many years"
years_input = gets.to_i
for years_input in (1..years_input)
    puts "Years Passed: Years = " + years_input.to_s
for m in (1..12)
    puts "Month: Month # = " + m.to_s
    puts "Inches of rainfall"
    rainfall_input = gets.to_i
end
end
puts "Total Months"
puts (years_input * 12).to_s
puts "Total Rainfall"

2 个答案:

答案 0 :(得分:2)

在这种情况下,您需要有一个存储“计数器”的地方total

puts "How many years"
years_input = gets.to_i
total_rainfall = 0

for years_input in (1..years_input)
  puts "Years Passed: Years = " + years_input.to_s
  for m in (1..12)
      puts "Month: Month # = " + m.to_s
      puts "Inches of rainfall"
      total_rainfall += gets.to_i
  end
end

puts "Total Months"
puts (years_input * 12).to_s

puts "Total Rainfall"
puts total_rainfall

答案 1 :(得分:1)

@Danilo已经回答了您的问题,所以让我建议您如何以更像Ruby的方式编写代码。首先,我要提到for循环在Ruby编码器中从未使用过。相反,我们使用枚举数(例如each,在这里为timessum)和块。这部分是为了将信息隐藏在块内,以避免在块外窥视。

require 'date'

puts "How many years?"
nbr_years = gets.to_i
puts "Number of years: #{nbr_years}"

nbr_years.times do
  puts "Which year?"
  y = gets.to_i
  tot = (1..12).sum do |m|
    puts "How many inches of rainfall in #{Date::MONTHNAMES[m]}, #{y}?"
    gets.to_f
  end
  puts "Total rainfall in #{y} was #{tot} inches"
end
#{nbr_years}中的

"Number of years: #{nbr_years}"通过计算nbr_yearsnbr_years.to_s转换为字符串。 (请参见Integer#to_s)。这就是字符串插值。如果nbr_years是一个数组,将应用Array#to_s,依此类推。

Date中搜索“ MONTHNAMES”,您会发现为方便起见已定义了Date::MONTHNAMES(在多个与日期相关的常量中):

Date::MONTHNAMES
  #=> [nil, "January", "February", "March", "April", "May", "June",
  #    "July", "August", "September", "October", "November", "December"]

在纯Ruby中,我们需要include 'date'来访问该常量(Rails不需要该常量)。

nil只是一个占位符。 Date::MONTHNAMES[0]从未被编码人员引用。

请注意,对于每月降雨量的英寸数,您需要gets.to_f而不是gets.to_i

我们可以通过将gets语句替换为生成的值来模拟此代码。

y = 2015
puts "How many years?"
nbr_years = 2
puts "Number of years: #{nbr_years}"

nbr_years.times do
  puts
  puts "Which year?"
  y += 1
  tot = (1..12).sum do |m|
    puts "How many inches of rainfall in #{Date::MONTHNAMES[m]}, #{y}?"
    f = (10 * rand).round(2)
    puts "#{f} inches of rainfall in #{Date::MONTHNAMES[m]}, #{y}?"
    f 
  end
  puts "Total rainfall in #{y} was #{tot} inches"
end

将显示以下内容(较小的编辑后)。

Which year?
How many inches of rainfall in January, 2016?
3.12 inches of rainfall in January, 2016?
How many inches of rainfall in February, 2016?
2.64 inches of rainfall in February, 2016?
...
How many inches of rainfall in December, 2016?
4.48 inches of rainfall in December, 2016?
Total rainfall in 2016 was 60.71 inches

Which year?
How many inches of rainfall in January, 2017?
7.15 inches of rainfall in January, 2017?
... 
How many inches of rainfall in December, 2017?
7.87 inches of rainfall in December, 2017?
Total rainfall in 2017 was 36.31 inches