M
Max Norman
As an exercise out of Chris Pine's 'Learning to Program,' I've attempted
to build a program that calculates the number of leap years between two
given years. Here is my code:
puts 'Use this calculator to determine the number of leap years in a
specific period.'
total = 0 # total number of leap years
puts 'Enter the first year below:'
year_one = gets.chomp.to_i
puts 'Enter the second year below:'
year_two = gets.chomp.to_i
while year_one.to_i < year_two.to_i
if year_one%4 == 0
if year_one%100 != 0 || year_one%400 == 0
total = total + 1
year_one = year_one+ 1
else
year_one = year_one+ 1
end
end
end
puts 'Between ' + year_one.to_s + ' and ' + year_two.to_s + ', there
were '
puts total.to_s + ' leap years.'
-
This is a different approach than Pine takes (most of my attempts are
formulated differently, but based around the right concept). He does
this:
puts 'Pick a starting year (like 1973 or something):'
starting = gets.chomp.to_i
puts 'Now pick an ending year:'
ending = gets.chomp.to_i
puts 'Check it out... these years are leap years:'
year = starting
while year <= ending
if year%4 == 0
if year%100 != 0 || year%400 == 0
puts year
end
end
year = year + 1
end
-
What's going wrong?
to build a program that calculates the number of leap years between two
given years. Here is my code:
puts 'Use this calculator to determine the number of leap years in a
specific period.'
total = 0 # total number of leap years
puts 'Enter the first year below:'
year_one = gets.chomp.to_i
puts 'Enter the second year below:'
year_two = gets.chomp.to_i
while year_one.to_i < year_two.to_i
if year_one%4 == 0
if year_one%100 != 0 || year_one%400 == 0
total = total + 1
year_one = year_one+ 1
else
year_one = year_one+ 1
end
end
end
puts 'Between ' + year_one.to_s + ' and ' + year_two.to_s + ', there
were '
puts total.to_s + ' leap years.'
-
This is a different approach than Pine takes (most of my attempts are
formulated differently, but based around the right concept). He does
this:
puts 'Pick a starting year (like 1973 or something):'
starting = gets.chomp.to_i
puts 'Now pick an ending year:'
ending = gets.chomp.to_i
puts 'Check it out... these years are leap years:'
year = starting
while year <= ending
if year%4 == 0
if year%100 != 0 || year%400 == 0
puts year
end
end
year = year + 1
end
-
What's going wrong?