闰年运动(Chris Pine):帮助/审查

时间:2017-05-14 07:21:43

标签: ruby

我是编程的新手,只是在闰年"在Chris Pine的网站上练习。

  1. 在我的while循环中包含以下代码是否正确处理此问题?

    and start = start.to_i + 1
    
  2. 如果节目是闰年,我就无法在我的列表第一年puts获得该节目。

  3. puts 'Enter start year...'
    start = gets.chomp
    
    puts 'Enter end year...'
    last = gets.chomp
    
    puts 'Your leap year selection...'
    
    while start.to_i <= last.to_i and start = start.to_i + 1
        if (start % 4 == 0 and start % 100 != 0) or (start % 100 == 0 and 
            start > % 400 == 0)
            puts start
        end
    end
    

2 个答案:

答案 0 :(得分:2)

首先,您的代码无法运行,因为它始终不记得使用start.to_i将字符串start用作数字。而不是经常进行转换,立即转换它。根据经验,尽早清理数据会使代码更简单。

puts 'Enter start year...'
start = gets.chomp.to_i

puts 'Enter end year...'
last = gets.chomp.to_i

现在startlast是数字......等待,startlast?制作startendfirstlast。好名声很重要。我希望您尝试end并且它无效,因为它是关键字。所以firstlast

让我们来看看。

while first <= last and first = first + 1
    ...
end

我们要做的是从first迭代到last。问题是first <= last and first = first + 1甚至在循环运行之前就会被评估,因此first已经递增。这就是为什么你没有进入第一年。

可以通过将递增放在循环的末尾来来修复它。

while first <= last
    ...
    first = first + 1
end

现在检查first <= last,进行闰年计算,然后才增加first

但是在Ruby中通常会避免使用这种循环方式。相反,Ruby提供了range operator来迭代。获得范围后,可以调用其上的each method来遍历每个元素。

(first..last).each do |year|
    ...
end

firstlast的每个号码都会分配到year。然后你的其余代码工作正常!

(first..last).each do |year|
    if (year % 4 == 0 and year % 100 != 0)   or
       (year % 100 == 0 and year % 400 == 0)
        puts year
    end
end

答案 1 :(得分:0)

首先要做的事情:欢迎使用Programming和StackoverFlow。我希望你在旅程中能获得最大的快乐:)。

至于运动, 你的方法是正确的,但你错了

while start.to_i <= last.to_i and start = start.to_i + 1

这个表达式是一个赋值:

start = start.to_i + 1 

增加此变量的值并跳过检查第一个值。

您可以在while循环体内进行增量:

  1. 只有在完成初步检查后才能通过递增来测试第一年是否为闰年:

     puts 'Enter start year...'
     start = gets.chomp
    
     puts 'Enter end year...'
     last = gets.chomp
    
     puts 'Your leap year selection...'
    
     while start.to_i <= last.to_i 
       if (start % 4 == 0 and start % 100 != 0) or (start % 100 == 0 and 
     start > % 400 == 0)
        puts start
       end
      start = start.to_i + 1
     end
    
  2. 我希望这会有所帮助。