Ruby 编程一段时间每天一分钱

Ruby programming double a penny a day for period of time

我是新手,三个星期以来 Ruby 作为我的第一语言。这是我已有的代码:

=begin
this program is to calculate doubling a penny a day for thirty one days
=end

puts "how many days would you like to calculate"
days = gets.chomp.to_i

i = 1
    loop do
    puts "#{i}"
    break i >=100
end

我尝试使用 ** 因为这是指数使用的语法。我也考虑过 until 循环,但我最困难的是如何在给定时间内每天将每个整数加倍。

我也试过"#{i**2}""#{i**i}",我这两天试过google这个问题,没用。

尝试:

# Display the question to the user in the terminal
puts 'How many days would you like to calculate?'

# Get the number of days from stdin
days = gets.chomp.to_i

# starting at 1 and up to the number of days start doubling. Reduce returns the result back to itself, thus doubling the return of each number until you have reached the up to limit.
result = 1.upto(days).reduce { |start| start * 2 }

# Put the result
puts result

这里不需要任何循环。一个力量呢?如果你想在31天内翻倍1便士,你需要计算2^30:

puts "how many days would you like to calculate"
days = gets.chomp.to_i
puts 2 ** (days - 1)

可以使用简单的位移操作来完成。二进制值“1”左移n次用于计算2^n.

puts "how many days would you like to calculate"
days = gets.chomp.to_i
puts 1 << (days - 1)
31.times.reduce 1 do |a| a * 2 end
#=> 2147483648