在 PowerShell 中进行整数除法的最简单方法是什么?这样参数就是整数,结果也是整数。
在 C++ 中,例如115/10
。
最佳答案
对于真正的整数除法,请使用 System.Math.Truncate
并将结果转换为[int]
:
[int] [Math]::Truncate(115 / 10) # -> 11
或者,使用 System.Math.DivRem
,它直接返回一个 [int]
(或 [long]
):
[Math]::DivRem(115, 10, [ref] $null) # -> 11
在 PowerShell (Core) 7+ ,可以使用返回元组的其他整数类型特定重载,因此您可以选择使用:
# PowerShell 7+ only.
[Math]::DivRem(115, 10)[0] # -> 11
PowerShell 根据需要扩展数值类型,并切换到 [double]
与整数操作数(任何整数类型,例如 [int]
)相除,结果是余数。
将除法结果转换为 [int]
(例如 [int] (115/10)
)不相同使用[Math]::Truncate()
,因为它执行半到偶舍入 - 请参阅 this answer了解详情。
关于powershell - PowerShell 中的整数除法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77534160/