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

时间:2015-01-08 14:56:11

标签: ruby

我是新手,三个人将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}",过去2天我试图谷歌解决这个问题,但无济于事。

4 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

这里你不需要任何循环。权力怎么样?如果你想在31天内加倍1便士,你需要计算2 ^ 30:

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

答案 2 :(得分:0)

尝试:

# 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

答案 3 :(得分:0)

31.times.reduce 1 do |a| a * 2 end
#=> 2147483648