操场swift EXC_错误_指令错误

操场swift EXC_错误_指令错误,swift,swift-playground,Swift,Swift Playground,我有以下测试代码 import Foundation var n = 5 let binSlots = 64 var numOfOnes = 0 var inSequence = false func toThePower(number: Int, power: Int) -> Int { var ans = number for _ in 1..<power { ans = ans * number } return ans

我有以下测试代码

import Foundation

var n = 5

let binSlots = 64
var numOfOnes = 0
var inSequence = false

func toThePower(number: Int, power: Int) -> Int {
    var ans = number
    for _ in 1..<power  {
        ans = ans * number
    }
    return ans
}

// the following line is fine
if n <= toThePower(number: 2, power: 4) {
    print("ok")
}

for i in stride(from: binSlots, through: 0, by: -1) {
    // the following line produces this error:
    // // error: Execution was interrupted, reason: 
    // EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).
    let pCalc = toThePower(number: 2, power: i) 

    if n >= pCalc {
        n = n - pCalc
        numOfOnes += 1
        inSequence = true
    }
    else {
        if inSequence {
            break
        }
    }
}
<代码>导入基础 变量n=5 让我们来看一看64 var numOfOnes=0 var insesequence=false 函数到功率(数字:Int,功率:Int)->Int{ var ans=数量
对于1..中的uuu,您的错误是从
中的这一行到power
函数:

for _ in 1..<power  {
结果是,您调用
toThePower
函数时,电源已关闭,包括0

0小于1,因此发生崩溃

更改:

for i in stride(from: binSlots, through: 0, by: -1) {
致:


为了避免崩溃。

编辑您的问题,并讨论您在使用调试器单步执行代码时发现的问题。由于swift的所有智能,类似这样的东西让我错过了“C”。感谢@maddyhmm,有一秒钟我认为这样做很有效,但没有成功。甚至检查
power
的值,如果值为0,则返回1没有解决此问题。我还将
改为power()
函数循环为使用
stride(:)
,但运气不好:(好。问题是计算2^63或2^64时出错。我将代码改为使用
UInt
,因为所有结果都是

for i in stride(from: binSlots, through: 0, by: -1) {
for i in stride(from: binSlots, through: 0, by: -1) {
for i in stride(from: binSlots, through: 1, by: -1) {