为什么 PowerShell 中的整数按数字进行比较? [英] Why do integers in PowerShell compare by digits?
本文介绍了为什么 PowerShell 中的整数按数字进行比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的代码会告诉你你的猜测数字是高于还是低于随机生成的数字,但它似乎只在其中一个小于 10 时比较数字的前几位.
My code tells you whether your guessed number is higher or lower than a randomly generated number, but it seems to only compare the first digits of the number when one of them is below 10.
[int]$GeneratedNum = Get-Random -min 1 -max 101
Write-Debug $GeneratedNum
$isQuitting = $false
Do{
[int]$Input = Read-Host "Take a guess!"
If($Input -lt $GeneratedNum){Write-Output "Too Low"}
If($Input -gt $GeneratedNum){Write-Output "Too High"}
If($Input -eq $GeneratedNum){Write-Output "Good Job!"; $isQuitting = $true}
} Until($isQuitting -eq $true)
例如,当 $GeneratedNum = 56
和 $Input = 7
时,它返回 "Too High"
For example, when the $GeneratedNum = 56
and $Input = 7
, it returns "Too High"
推荐答案
这是因为您将字符串与整数进行比较.顺序很重要.
This is because you're comparing a string to an integer. The order matters.
"56" -lt 7
其实是一样的:
"56" -lt "7"
或者:
56 -lt "7"
会给你正确的结果.PowerShell 尝试将右侧的参数强制转换为左侧的类型.
would give you the correct result. PowerShell tries to coerce the right side argument to the type of the left side.
您可以尝试显式转换:
[int]$Input -lt $GeneratedNum
这篇关于为什么 PowerShell 中的整数按数字进行比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文