加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby没有将Fixnum隐式转换为String(TypeError)

发布时间:2020-12-16 20:47:56 所属栏目:百科 来源:网络整理
导读:我正在尝试从克里斯·松的“学习计划”书中回答以下问题: Leap years. Write a program that asks for a starting year and an ending year and then puts all the leap years between them (and including them,if they are also leap years). Leap years
我正在尝试从克里斯·松的“学习计划”书中回答以下问题:

Leap years. Write a program that asks for a starting year and an ending year and then puts all the leap years between them (and including them,if they are also leap years). Leap years are years divisible by 4 (like 1984 and 2004). However,years divisible by 100 are not leap years (such as 1800 and 1900) unless they are also divisible by 400 (such as 1600 and 2000,which were in fact leap years). What a mess!

当我运行我的代码时,我收到以下错误:

leap_year.rb:12:in’:没有将Fixnum隐式转换为String(TypeError)
从leap_year.rb:12:在’

这是我的代码:

#leap years

puts 'What is the starting year?'
starting_year = gets.chomp
puts 'What is the ending year?'
ending_year = gets.chomp

while starting_year <= ending_year
  if starting_year%4 == 0 && (starting_year%100 != 0 && starting_year%400 == 0)
    puts starting_year 
  end 
  starting_year+=1
end

解决方法

添加一个 .to_i到您的gets.chomp调用.你正在尝试对文本进行数学运算.当从控制台输入时,一切都以文本形式开始,即使它是数字文字.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读