新手问题 关于 while 的疑问

chankaward · 2012年10月15日 · 最后由 chankaward 回复于 2012年10月15日 · 2238 次阅读
puts "What year do you want to start?"
start_year = gets.chomp 
puts "What year do you want to end ?"
end_year = gets.chomp

if start_year.to_i > end_year.to_i  
    puts "Starting year should smaller than ending year!"
else
    puts "leap year between " + start_year + " and " + end_year +" :"
end

while start_year.to_i < end_year.to_i
    while ((start_year.to_i%4 == 0 and start_year.to_i%100 != 0) or (start_year.to_i%100==0 and start_year.to_i%400 == 0))
        puts start_year
        start_year = start_year.to_i + 1 # 请问这里应该怎样理解呢?
    end
    start_year = start_year.to_i + 1 # 请问这里应该怎样理解呢?
end

start_year 本来是 string 类型的,但是为了比较大小,要转成 int 型,比较后要 +1,然后再把值赋回给 start_year

楼主格式化代码要这样

ruby if start_year.to_i > end_year.to_i puts "Starting year should smaller than ending year!" else puts "leap year between " + start_year + " and " + end_year +" :" end

效果

if start_year.to_i > end_year.to_i
  puts "Starting year should smaller than ending year!"
else
  puts "leap year between " + start_year + " and " + end_year +" :"
end

#2 楼 @Rei 哎呀,受教了。

#1 楼 @Teddy 为什么比较后要 +1 呢?

需要 登录 后方可回复, 如果你还没有账号请 注册新账号