我到底做错了什么,减法似乎很好,但加法和乘法似乎根本不起作用。
如何让它正确进行计算并允许 if 语句也起作用,因为即使数字大小不正确,它似乎也总是运行。
$a = Read-Host "What is your name?"
$b = Read-Host "Enter a 2 digit number"
$c = Read-Host "Enter a 3 digit number"
if (($b -ge 10) -and ($b -le 99) -and ($c -ge 100) -and ($c -le 999)){
$d = $b + $c
$e = $b * $c
$g = $b - $c
$d
$e
$g
Write-host "Here you go $a"
}
else {
write-host "Enter the numbers correctly"
}
最佳答案
<强> Read-Host
始终输出一个字符串。
为了将其输出(或任何字符串)视为数字,您必须将其显式转换为一:
$a = Read-Host "What is your name?"
# Note: Add error handling with try / catch
# and a retry loop to deal with invalid input.
[int] $b = Read-Host "Enter a 2 digit number"
[int] $c = Read-Host "Enter a 3 digit number"
上述类型约束变量$b
和$c
到整数值(通过将 [int]
转换到赋值中目标变量的左侧),这会自动转换 Read-Host
的[string]
输出到[int]
.
这也适用于强制转换:[int] '2' -lt 10
是 $true
(如果没有 [int]
转换,由于词法比较,它将是 $false
)。
用一个具体的例子来拼写它,直到输入两位数(十进制)数字为止进行提示:
do {
try {
[int] $b = Read-Host "Enter a 2 digit number"
} catch {
continue # Not a number - stay in the loop to prompt again.
}
if ($b -ge 10 -and $b -le 99) { break } # OK, exit the loop.
} while ($true)
注意:严格来说,[int]
cast 接受任何可以在 PowerShell 中用作数字文字的内容,其中包括十六进制表示形式,例如 0xA
,以及带有类型后缀的数字,例如 10l
- 参见this answer了解更多信息。
至于你尝试过的:
除了 -
(和 /
),代码中使用的所有运算符都有特定于字符串的重载(含义);请注意,LHS 的类型为 [string]
就足够了。 触发此行为。[1]
-lt
/-ge
与字符串进行词法比较;例如,'10' -gt '2'
产量$false
,因为,在词法排序中,字符串'10'
位于字符串'2'
之前.-and
/-or
将空字符串视为$false
,以及任何非空字符串$true
;例如,
'0' -and '0'
是$true
,因为'0'
是一个非空字符串。+
执行字符串连接;例如,'1' + '0'
是'10'
.*
执行字符串复制;例如,'1' * 3
是'111'
- 左侧的重复次数与右侧的数字指定的次数相同;请注意'1' * '3'
工作原理相同,因为 RHS 被强制为[int]
在这种情况下。-
和/
是唯一的异常(exception):如果可能的话,它们总是执行数字运算;例如,'10' - '2'
产量8
,和'10' / '2'
产量5
,因为两个操作数都隐式转换为[int]
s。
[1] 通常,操作的LHS决定两个操作数的数据类型,导致RHS被强制为相同的如有必要,请键入。
关于Powershell Read-Host 无法正确加法或乘法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58718111/