我在 Swift 中创建了一个函数来求解二次函数并给出解决方案。我不知道如何调整我的函数,以便它给出想象的解决方案而不是打印,"没有真正的解决方案"。
我对编程相对较新,可以使用一些帮助。这是我的代码:
func quadraticFormulaSolver(variableA a: Double, variableB b: Double, variableC c: Double) -> (Double, Double) {
let firstSolution: Double = (-b + sqrt((b * b) + (-4.0 * a * c))) / 2.0
let secondSolution: Double = (-b - sqrt((b * b) + (-4.0 * a * c))) / 2.0
let checkSolution: Double = sqrt((b * b) + (-4.0 * a * c))
if checkSolution > 0 {
print("There are two real solutions and they are (firstSolution) and (secondSolution)")
return(firstSolution, secondSolution) }
guard firstSolution != 0.0 else {
print("There is one real solution and it is (firstSolution)")
return(firstSolution, secondSolution) }
guard checkSolution < 0 else {
print("There are no real solutions")
return(firstSolution, secondSolution) }
return(firstSolution, secondSolution)
}
由于您的函数可以返回几个不同的选择,因此让我们创建一个Enum
来表示这些选项:
enum QuadraticSolution {
case TwoReal(firstSolution: Double, secondSolution: Double)
case OneReal(solution: Double)
case TwoNonReal
}
我们一会儿再来TwoNonReal
。
您的函数现在可以返回此枚举的实例:
func quadraticFormulaSolver(variableA a: Double, variableB b: Double, variableC c: Double) -> QuadraticSolution {
为了使代码更具可读性,让我们过滤掉判别式:
let discriminant = (b * b) - (4.0 * a * c)
然后我们可以对它使用 switch
语句。如果它是积极的,你就有两个真正的根源。如果为零,则有一个实数(重复)根。如果它是负数,则有两个非实根:
switch discriminant {
case _ where discriminant > 0:
let firstSolution = (-b + sqrt(discriminant)) / (2.0 * a)
let secondSolution = (-b - sqrt(discriminant)) / (2.0 * a)
return .TwoReal(firstSolution: firstSolution, secondSolution: secondSolution)
case _ where discriminant == 0:
let solution = (-b) / (2.0 * a)
return .OneReal(solution: solution)
default: // discriminant is negative
return .TwoNonReal
}
}
Swift 没有非实数的内置类型。与其重新发明轮子,我建议你在你的应用程序中嵌入swift-pons
。
完成此操作后,您可以更改TwoNonReal
枚举以返回两个Complex
数字:
case TwoNonReal(firstSolution: Complex, secondSolution: Complex)
然后你可以这样计算它们:
default: // discriminant is negative
let base = (-b) / (2.0 * a)
let firstSolution = base + (Complex.sqrt(-1.0 * discriminant)) / (2.0 * a)
let secondSolution = base - (Complex.sqrt(-1.0 * discriminant)) / (2.0 * a)
return .TwoNonReal(firstSolution: firstSolution, secondSolution: secondSolution)
}