为什么PowerShell中的整数按数字进行比较? [英] Why do integers in PowerShell compare by digits?

查看:228
本文介绍了为什么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

实际上与以下内容相同:

Is actually the same as:

"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.

您可以尝试进行显式投射:

You might try an explicit cast:

[int]$Input -lt $GeneratedNum

这篇关于为什么PowerShell中的整数按数字进行比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆