我在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)
}
答案 0 :(得分:0)
由于您的功能可以返回一些不同的选项,因此我们要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)
}