代码是正确的,但有时我遇到了运行时错误

时间:2015-03-08 10:05:18

标签: swift random numbers cycle

我写了一个函数,在这个函数里面有一个开关,并且在每种情况下都有随机生成数字的操作 我在for循环中多次调用此函数并将结果复制到一个数组中,有时我在执行期间得到一个EXC_BAD_Instruction错误,我不明白为什么

我注意到如果周期越长,错误就越频繁出现,为什么? 我需要做什么才能在没有任何错误的更大周期内使用此代码?

var operationNumber = random() % 4  

switch operationNumber {
case 0:
    number1 = random() % (biggestN + 1)
    number2 = random() % (biggestN + 1)
    result = number1 + number2
    operation = "+"
case 1:
    number1 = random() % (biggestN + 1)
    number2 = random() % (number1 + 1)
    result = number1 - number2
    operation = "-"
case 2:
    number1 = (random() % (biggestN + 1))+1
    number2 = (random() % (number1/2))+1
    result = number1 * number2
    operation = "x"
case 3:
    result = random()%biggestN
    number1 = (random()%biggestN)*result
    number2 = number1 / result
    operation = "/"
default:
    break
}

在编辑器中,带错误的行是case 0,所以我认为错误在switch中

感谢您的回答

3 个答案:

答案 0 :(得分:2)

在案例3中,您可能会得到零除错。在这种情况下,您应断言result不为零。一种方法如下:

result = (random() % biggestN) + 1

编辑:

如果biggestN为零,也会发生同样的情况。所以我们可以更新到:

result = (random() % (biggestN + 1)) + 1

答案 1 :(得分:0)

解决:

case 0:
    number1 = random() % (biggestN + 1)
    number2 = random() % (biggestN + 1)
    result = number1 + number2
    operation = "+"
case 1:
    number1 = random() % (biggestN + 1)
    number2 = random() % (number1 + 1)
    result = number1 - number2
    operation = "-"
case 2:
    number1 = (random() % (biggestN + 1))+1
    number2 = (random() % (biggestN + 1))
    result = number1 * number2

    operation = "x"
case 3:
    result = (random()%biggestN)+1
    number1 = (random()%biggestN)*result
    number2 = number1 / result
    operation = "/"

答案 2 :(得分:0)

Junior很接近,基本上问题是/和%的分母(左手操作数)必须是非零的,并且你有多个不满足条件的情况。最简单的解决方法是将random的使用情况替换为arc4random_uniform,这也可以让您更好地分发:

func pick(range:Int) -> Int {
    return Int(arc4random_uniform(UInt32(range)))
}

func sampler(biggestN:Int) {
    var operationNumber = pick(4)
    var result:Int = 0
    var number1:Int = 0
    var number2:Int = 0
    var operation:String = "X"

    switch operationNumber {
    case 0:
        number1 = pick(biggestN + 1)
        number2 = pick(biggestN + 1)
        result = number1 + number2
        operation = "+"
    case 1:
        number1 = pick(biggestN + 1)
        number2 = pick(number1 + 1)
        result = number1 - number2
        operation = "-"
    case 2:
        number1 = pick(biggestN + 1) + 1
        number2 = pick(number1 / 2) + 1
        result = number1 * number2
        operation = "x"
    case 3:
        result = pick(biggestN) + 1
        number1 = pick(biggestN) * result
        number2 = number1 / result
        operation = "/"
    default:
        break
    }
}