Ruby 闰年练习(Chris Pine):帮助/回顾
我对编程一无所知,只是在Chris Pine的网站上完成“闰年”练习Ruby 闰年练习(Chris Pine):帮助/回顾,ruby,Ruby,我对编程一无所知,只是在Chris Pine的网站上完成“闰年”练习 在while循环中包含以下代码是否是正确的方法 and start = start.to_i + 1 如果是闰年,我无法让程序将第一年放在我的列表中 输入“开始年份…” start=get.chomp 输入“输入年底…” last=get.chomp 将“您的闰年选择…” 而start.to_i%400==0) 开始 结束 结束 首先,您的代码不会运行,因为它并不总是记得使用start。to_i将字符串start用作数字。
and start = start.to_i + 1
输入“开始年份…”
start=get.chomp
输入“输入年底…”
last=get.chomp
将“您的闰年选择…”
而start.to_i%400==0)
开始
结束
结束
首先,您的代码不会运行,因为它并不总是记得使用start。to_i
将字符串start
用作数字。与其不断地进行转换,不如立即进行转换。根据经验,尽早清理数据将使代码更简单
puts 'Enter start year...'
start = gets.chomp.to_i
puts 'Enter end year...'
last = gets.chomp.to_i
现在start
和last
是数字。。。等一下,开始
和最后一次
?使开始
和结束
或第一个
和最后一个
。好名声很重要。我希望您尝试了end
,但没有成功,因为它是一个关键字。所以第一个
和最后一个
让我们看看这个
while first <= last and first = first + 1
...
end
现在它首先检查
first第一件事:欢迎使用编程和StackoverFlow。我希望您在整个旅程中都能获得最大的快乐:)
至于演习,,
你的方法是正确的,但你犯了一个错误
while start.to_i <= last.to_i and start = start.to_i + 1
这将增加此变量的值,并跳过对第一个值的检查
您可以在while循环体中执行该增量:
只有在完成初始检查后,才能通过增加闰年来测试第一年是否为闰年:
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
输入“开始年份…”
start=get.chomp
输入“输入年底…”
last=get.chomp
将“您的闰年选择…”
而start.to_i%400==0)
开始
结束
start=start.to_i+1
结束
我希望这能有所帮助。大家好,欢迎来到Stack Overflow!你能用相关练习的链接编辑你的问题吗?或者解释一下这是怎么做的?“while语法不允许将赋值放在它的条件部分。”注意,这是不正确的。我相信是Python故意在一段时间内不允许赋值。在Ruby中,您可以使用任何表达式作为条件,并且可以包含赋值。表达式的结果将用作条件。在条件中赋值是正常的,如而line=getline()
,但在Ruby等具有良好迭代器的语言中不需要这样做。@Schwern感谢您提供的信息。在Ruby中,除null和false之外的所有值都是true。这就是为什么即使赋值也可以作为布尔值进行计算。@Schwern:更准确地说,如果赋值属于某种类型(我认为右边是一个常量值),Ruby也会警告不要在条件中赋值,但通常不会有问题:如果a=1,则放置a,如果a=b没有问题,则将a放入。此外,和和和或通常不受欢迎,支持&
和|
,除非有人将它们用作流控制,因为它们的不同优先级曾经是常见的错误源。
(first..last).each do |year|
...
end
(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
while start.to_i <= last.to_i and start = start.to_i + 1
start = start.to_i + 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