gpt4 book ai didi

powershell - 为什么Powershell将简单的整数运算转换为两倍?

转载 作者:行者123 更新时间:2023-12-02 23:17:12 26 4
gpt4 key购买 nike

我使用Powershell已有一段时间了,偶然发现了PSKoan项目:

https://github.com/vexx32/PSKoans

在第一个可口可乐中,我发现了一些奇怪的行为,我无法向自己解释。
关于数字类型的可口可乐试图讲解powershell如何在某些操作上将变量类型从int动态转换为long,从int动态转换为double。

因此,我填写了此特定的瘟疫测试的空白(如在本类(class)中预期的那样):

 It 'can be a larger number if needed' {
<#
Integers come in two flavours:
- int (Int32)
- long (Int64)

If an integer value exceeds the limits of the Int32 type, it is
automatically expanded to the larger Int64 type.
#>

# What exactly are the limitations of the [int] type?
$MaxValue = [int]::MaxValue
$MinValue = [int]::MinValue

2147483647 | Should -Be $MaxValue
-2147483648 | Should -Be $MinValue

# If you enter a number larger than that, the type should change.
$BigValue = $MaxValue +1
$BigValue | Should -BeOfType [long]
$BigValue | Should -BeGreaterThan $MaxValue

$SmallValue = $MinValue -1
$SmallValue | Should -BeOfType [long]
$SmallValue | Should -BeLessThan $MinValue
}

使用show-karma让PSKoans发挥其魔力:

The answers you seek...
Expected the value to have type [long] or any of its subtypes, but got 2147483648 with type [double].


可以将其缩小为以下示例,但我不理解:


为什么这是现在的两倍,而不是很长?

我正在使用PS 5.1:

enter image description here

附言它来晚了,所以也许我想念一些非常明显的东西,我已经为大脸掌做好了准备;)

最佳答案

实际上,在表达式(计算)上下文中,PowerShell的确会自动将扩展超过最大值的任何内容。 [int] / [uint](32位有符号/无符号整数)或[long] / [ulong] (64位)到的值[double] ,易于验证[1]:

# Ditto for [uint], [long], [ulong]
PS> ([int]::MaxValue + 1).GetType().Name
Double # [double]

相比之下,小于[int]整数类型的最大值被提升为[int](System.Int32)。计算中超出了值:
# Ditto for [sbyte], [int16], [uint16]
PS> ([byte]::MaxValue + 1).GetType().Name
Int32 # same as: [int]

仅有数字文字会升为下一个最大的有符号整数类型,而[int]之外的值会出现:

注意:任何数值介于[int]::MinValue[int]::MaxValue之间的数字文字(即使它可以适合较小的整数类型)也默认为[int],即32位带符号整数(System.Int32)。
# Note: 2147483648 is the result of ([int]::MaxValue + 1)
PS> (2147483648).GetType().Name
Int64 # same as: [long]

并且,如果数字文字超出[long]::MaxValue的值,则会升为[decimal]:
# Note: 9223372036854775808 is the result of ([long]::MaxValue + 1)
PS> (9223372036854775808).GetType().Name
Decimal # [decimal]

只有当您超过[decimal]::MaxValue]时,才会升级为[double]-可能会导致精度下降:
# Note: 79228162514264337593543950336 is the result of ([decimal]::MaxValue + 1)
PS> (79228162514264337593543950336).GetType().Name
Double # [double]

直接输出上述值使转换为[double]的操作立即显而易见,因为输出格式使用指数表示法:7.92281625142643E+28
[1]奇怪的是,尝试计算超出[decimal]::MaxValue的值失败,从而导致语句终止错误:([decimal]::MaxValue + 1).GetType().Name

关于powershell - 为什么Powershell将简单的整数运算转换为两倍?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62459576/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com