为什么这段代码会出错并且无法打印结果?

问题描述 投票:0回答:2

谁能指出下面代码的问题吗? 我无法让它在 Xcode Playground 中正常运行,任何帮助将不胜感激。

func calculator(a:Int, b:Int) {
  let a = Int(readLine()!)! //First input
  let b = Int(readLine()!)! //Second input

  add(n1: a, n2: b)
  subtract(n1: a, n2: b)
  multiply(n1: a, n2: b)
  divide(n1: a, n2: b)
  
}

//Write your code below this line to make the above function calls work.

func add(n1:Int, n2:Int){
    print(n1+n2)
}

func subtract(n1:Int, n2:Int){
    print(n1-n2)
}
func multiply(n1:Int, n2:Int){
    print(n1*n2)
}
func divide(n1:Int, n2:Int){
    let a1 = Double(n1)
    let a2 = Double(n2)
    print(a1 / a2)
}


calculator(a:3, b:4)

错误:

错误:执行被中断,原因:EXC_BAD_INSTRUCTION(代码=EXC_I386_INVOP,子代码=0x0)。 __lldb_expr_1/MyPlayground.playground:4:致命错误:在解包可选值时意外发现 nil

期望它简单地打印加、减、乘、除的结果。

swift xcode
2个回答
0
投票

错误在于您创建了无用的常量,并且没有在其中传递值。正确的方法是在调用函数时在函数的参数中传递一个值

func calculator(a:Int, b:Int) {
      
      add(n1: a, n2: b)
      subtract(n1: a, n2: b)
      multiply(n1: a, n2: b)
      divide(n1: a, n2: b)
      
    }
    
    //Write your code below this line to make the above function calls work.
    
    func add(n1:Int, n2:Int){
        print(n1+n2)
    }
    
    func subtract(n1:Int, n2:Int){
        print(n1-n2)
    }
    func multiply(n1:Int, n2:Int){
        print(n1*n2)
    }
    func divide(n1:Int, n2:Int){
        let a1 = Double(n1)
        let a2 = Double(n2)
        print(a1 / a2)
    }

-1
投票

我有同样的问题,但主要是第一个功能

func add(n1: Int, n2: Int) {

}

这不起作用。我错过了什么吗?

© www.soinside.com 2019 - 2024. All rights reserved.