坏指令arc4random_uniform

时间:2017-05-09 14:32:13

标签: ios swift

我试图对百分比做点什么,但我认为我做错了。

let randomNum = arc4random_uniform(25) + 71
let wrongNumber = 100 - Int(randomNum)
let firstWrong = wrongNumber - 10
var first = arc4random_uniform(UInt32(firstWrong))
var second = arc4random_uniform(UInt32(wrongNumber) - first)
var third = arc4random_uniform(UInt32(wrongNumber) - (first + second))
let plus = (UInt32(wrongNumber) - (first + second + third)) / 3
first = first + plus
second = second + plus
third = third + plus
let total = randomNum + first + second + third
if (total < 100) {
    first += (100 - total)
}

It sometimes gives this BAD INSTRUCTION error

And it usually works fine

1 个答案:

答案 0 :(得分:2)

你的逻辑是完全有缺陷的,考虑前几行:

let randomNum = arc4random_uniform(25) + 71 // values 71 ... 95
let wrongNumber = 100 - Int(randomNum) //values 5 ... 29
let firstWrong = wrongNumber - 10 // -5 ... 19

最大randomNum95。然后wrongNumber5firstWrong-5

然后

var first = arc4random_uniform(UInt32(firstWrong))
-5转换为无符号数时,

必须崩溃。

如果值变为负数,则其他行上可能会发生类似的错误。