Unable to execute command: Killed [duplicate]

2019-08-02 02:36发布

This question already has an answer here:

I'm using IBM's online Swift sandbox and I'm trying to run this code but it's giving me an error:

The code:

var a: Double = 1.0
var b: Double = 2.0
var c: Double = 3.0
var x: Double = 0.0

func x_func(a_var: Double, b_var: Double, c_var: Double) -> Double {

  x = (-b + (b^2 - 4*a*c)^(1/2))/(2*a)
  return x

}

print(x_func(a_var: a, b_var: b, c_var: c))
print(a)
print(b)
print(c)

The error:

<unknown>:0: error: unable to execute command: Killed
<unknown>:0: error: compile command failed due to signal (use -v to see invocation)

Could someone help me figure out what's wrong? I'm brand new to Swift, so I don't see an error here.

1条回答
Root(大扎)
2楼-- · 2019-08-02 03:26

Try using pow when you want to use exponents, the ^ doesn't work with Swift for that. With Swift ^ produces bitwise XOR - not exponent.

import Foundation

var a: Double = 1.0
var b: Double = 2.0
var c: Double = 3.0
var x: Double = 0.0

func x_func(a_var: Double, b_var: Double, c_var: Double) -> Double {

    x = (-b + pow((pow(b, 2) - 4*a*c), 1/2))/2*a
    return x

}

Make sure when using things like IBM Sandbox, or HackerRank or whatever to import Foundation framework! I know it's easy to forget and can cause a lot of headache if you do.

Also, unless you're doing extra computation in your x_func method that you're not showing, you're asking for parameters to be passed in that you don't even use. You can either get rid of the properties, or change the function to not take in any variables - it would probably be more efficient to get rid of the properties and change it to something like this:

import Foundation

func x_func(a: Double, b: Double, c: Double) -> Double {

    x = (-b + pow((pow(b, 2) - 4*a*c), 1/2))/2*a
    return x

}
查看更多
登录 后发表回答