2011-03-12 47 views
1

我剛開始學習ruby。 現在我試着去編寫一個小腳本,其播放montyhall問題 我有一個問題與代碼一個小紅寶石腳本的問題

numgames = 10000 # Number of games to play 
switch = true # Switch your guess? 
wins = 0 
numgames.times do doors = [0, 0, 0] # Three doors! 
doors[rand(3)] = 1 # One of them has a car! 
guess = doors.delete_at(rand(3)) # We pick one of them! 
doors.delete_at(doors[0] == 0 ? 0 : 1) # Take out one of the remaining doors that is not a car! 
wins += switch ? doors[0] : guess end 
puts "You decided #{switch ? "" : "not "}to switch, and your win % is #{wins.times()/numgames}" 

回答

0

wins是一個整數,所以你不需要.times.size,你這樣做,不過,要.to_f強制東西放到浮點模式:

wins.to_f/numgames 

如果你想有一個百分比,那麼你「馬上有100乘:

wins.to_f/numgames * 100 

你也應該適當地縮進代碼的可讀性,打破上去換行,使其更容易閱讀和便於解析器要弄清楚:

numgames = 10000 # Number of games to play 
switch = true # Switch your guess? 
wins = 0 
numgames.times do 
    doors = [0, 0, 0] # Three doors! 
    doors[rand(3)] = 1 # One of them has a car! 
    guess = doors.delete_at(rand(3)) # We pick one of them! 
    doors.delete_at(doors[0] == 0 ? 0 : 1) # Take out one of the remaining doors that is not a car! 
    wins += switch ? doors[0] : guess 
end 
puts "You decided #{switch ? "" : "not "}to switch, and your win % is #{100 * wins.to_f/numgames}" 
2

在最後一行的最後一行替換

wins.times() 

wins 

times返回Enumerator,這與分區不匹配。

+0

謝謝!但即時通訊仍然收到語法錯誤。 monty.rb:9:syntax error,unexpected')' ... nd你的勝利是#{wins.size()/ numgames}「 –

+0

你的括號是否平衡? – miku

+0

這是否意味着每一個缺口都被正確打開,關閉?然後是的! –

1

兩個問題:

首先,winsnumgames是整數,並且整數除法返回一個整數:

irb(main):001:0> 6632/10000 
=> 0 

因此,改變wins = 0wins = 0.0。這將強制進行浮點除法,這將返回浮點回答。第二,wins是一個數字,而不是數組。所以擺脫wins.times()wins.size()。兩者都是錯誤的。

有了這兩個變化,我始終得到約66%的勝利,這只是正好說明Marilyn vos Savant方式比我聰明。