【问题标题】:Guessing a number with if-else statement用 if-else 语句猜数字
【发布时间】:2018-08-08 21:51:38
【问题描述】:

我为猜数游戏编写了一个简短的 powershell 脚本。如下所示:

clear-host

$Guess = "11"

$response=read-host "Enter your guess"

if ($response -eq $guess)
{ 
    write-host "Congratulations"
}
else {
    write-host "Try again"
}

现在,如果我想这样做,例如在猜错一定次数后,猜错 3 次,程序将退出。我怎么能做到这一点?能否请您对这个问题有所了解?

【问题讨论】:

  • 你需要一个循环
  • 我无法做到这一点。你能告诉我吗?
  • 我应该在 IF 语句之前使用 do- until 循环吗???
  • 你应该在它周围使用它。就像将读取主机和 if 放在循环中一样。

标签: powershell scripting windows-scripting


【解决方案1】:

这是一个带有while循环的解决方案

$count = 0
$answered = $false
while ($count -lt 3 -and $answered -eq $false) {
    clear-host

    $Guess = "11"

    $response=read-host "Enter your guess"

    if ($response -eq $guess)
    { 
        $answered = $true
        write-host "Congratulations"
    }
    else {
        write-host "Try again"
    }
    $count++
}

【讨论】:

    猜你喜欢
    • 2017-04-01
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    • 2017-02-05
    • 1970-01-01
    • 2015-07-06
    • 2012-08-05
    相关资源
    最近更新 更多