gpt4 book ai didi

swift - 相同的 Int 在 Swift 中有不同的值,神秘的谜语

转载 作者:行者123 更新时间:2023-12-04 15:11:45 27 4
gpt4 key购买 nike

使用此代码:

let rand : Int = Int(arc4random())
NSLog("rand = %d %i %@ \(rand)",rand,rand,String(rand))

我明白了:

rand = -1954814774 -1954814774 2340152522 2340152522

为什么所有 4 个值都不相同?

最佳答案

arc4random 生成一个无符号的 32 位整数。 Int 在你的机器上可能是 64 位的,所以你得到相同的数字并且它不会溢出。但是 %i%dsigned 32 位格式说明符。参见 herehere .这就是为什么当 arc4random 返回一个大于 2^32-1 的数字(又名 Int32.max)时得到负数的原因。

例如,生成 2340152522 时,您在 %i 位置得到 -1954814774,因为:

Int32(bitPattern: 2340152522) == -1954814774

另一方面,将 Int 转换为 String 不会更改数字。 Int 是一个带符号的 64 位整数。

关于swift - 相同的 Int 在 Swift 中有不同的值,神秘的谜语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65107872/

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