gpt4 book ai didi

Ruby while 循环在满足条件时不会停止

转载 作者:数据小太阳 更新时间:2023-10-29 08:07:10 25 4
gpt4 key购买 nike

我开始学习 Ruby,我被我正在编写的这个程序困住了,它被认为是游戏“掷骰子”游戏的一小部分,至少无论如何,代码在第二个 while 循环甚至当随机骰子满足循环条件时。

这是不断循环的循环

while new_dice_sum != 7 or new_dice_sum != 11 or new_dice_sum != 2 or new_dice_sum != 3 or new_dice_sum != 12 or new_dice_sum != point
dice1 = 1 + rand(6)
dice2 = 1 + rand(6)
new_dice_sum = dice1.to_i + dice2.to_i

这是程序的完整代码。

input = ""
point = 0
balance = 100
Bet = 10
dice1 = 0
dice2 = 0
dice_sum = 0
new_dice_sum = 0
won = 0
lost = 0
while input != "Q"
print "Please choose R to roll the dice or Q to exit the game: "
input = gets.chomp.upcase
if input == "R"
if balance > 10
dice1 = 1 + rand(6)
dice2 = 1 + rand(6)
dice_sum = dice1.to_i + dice2.to_i
puts "First dice is #{dice1} while the second dice is #{dice2} both are a total of #{dice_sum}"
if dice_sum == 7 || dice_sum == 11
balance = balance + Bet
won = won + 1
puts "You won, Your new balance is #{balance}"
elsif dice_sum == 2 || dice_sum == 3 || dice_sum == 12
balance = balance - Bet
lost = lost + 1
puts "You lost, Your new balance is #{balance}"
else
point = dice_sum
while new_dice_sum != 7 or new_dice_sum != 11 or new_dice_sum != 2 or new_dice_sum != 3 or new_dice_sum != 12 or new_dice_sum != point
dice1 = 1 + rand(6)
dice2 = 1 + rand(6)
new_dice_sum = dice1.to_i + dice2.to_i
puts "In the new roll with your point #{point}, The first dice is #{dice1} while the second dice is #{dice2} both are a total of #{new_dice_sum}"
if new_dice_sum == 7 || new_dice_sum == 11
balance = balance + Bet
won = won + 1
puts "You won, Your new balance is #{balance}"
elsif new_dice_sum == 2 || new_dice_sum == 3 || new_dice_sum == 12
balance = balance - Bet
lost = lost + 1
puts "You lost, Your new balance is #{balance}"
elsif new_dice_sum == point
balance = balance + Bet
won = won + 1
puts "Your Total dice is equal to your point you won, your new balance is #{balance}"
end
end
end
else
puts "Your balance is not enough to place a bet, Your balance now is #{balance}"
end
elsif input != "Q"
puts "#{input} is not valid choice"
end
end
puts "Your current balance is #{balance}$ and you won #{won} times and lost #{lost} times"
exit

最佳答案

因为您正在对所有参数执行,所以即使它首先匹配,它也会通过而不匹配第二个。

variable != firstcondition 或 variable != secondcondition 更改 while 循环的逻辑 ...到!(变量 == 条件或变量 == 条件 ...)

关于Ruby while 循环在满足条件时不会停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40477449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com