首页 > 解决方案 > 该等式将无法迅速解决此错误的原因

问题描述

let a: Double  = 9.1
let b: Double  = -1.1
let c: Double  = 1.3
root1: Double = (b + sqrt((b * b) - 4 * a * c)/(2 * a)
root2: Double = (b + sqrt((b * b) - 4 * a * c)/(2 * a)
print(root1)
print(root2)

错误是:

/tmp/560B3FBA-E1E9-48E8-B069-8958D75A2043.L2LFYF/main.swift:16:6: error: consecutive statements on a line must be separated by ';'
root1: Double = (b + sqrt((b * b) - 4 * a * c)/(2 * a)
     ^
     ;
/tmp/560B3FBA-E1E9-48E8-B069-8958D75A2043.L2LFYF/main.swift:16:6: error: expected expression
root1: Double = (b + sqrt((b * b) - 4 * a * c)/(2 * a)
     ^
/tmp/560B3FBA-E1E9-48E8-B069-8958D75A2043.L2LFYF/main.swift:16:1: error: use of unresolved identifier 'root1'
root1: Double = (b + sqrt((b * b) - 4 * a * c)/(2 * a)
^~~~~

标签: iosswiftmath

解决方案


您之前忘记了“让”,root1并且root2

let a: Double  = 9.1
let b: Double  = -1.1
let c: Double  = 1.3
let root1: Double = (b + sqrt((b * b) - 4 * a * c)/(2 * a)
let root2: Double = (b + sqrt((b * b) - 4 * a * c)/(2 * a)
print(root1)
print(root2)

正如邓肯所指出的,还有一些我没有注意到的问题。

您可以通过查看判别式的符号来确定二次函数是否具有零个、一个或两个不同的实数根。由于我们将从一组相关值中计算多个值(判别式和最多两个根),因此这是使用struct.

在这里,我使用名为 ... 的结构对表示二次函数的三个 Double 进行建模QuadraticFunction。然后,您可以向该函数询问其判别式的值和解决方案。我还制作了一个帮助函数,它为解决方案构建了一个很好的英文描述。

import Foundation

struct QuadraticFunction {
    let a, b, c: Double
    
    var discriminant: Double { b*b - 4*a*c }
    
    enum Roots {
        case two(Double, Double)
        case one(Double)
        case none
    }
    
    func solve() -> Roots {
        switch self.discriminant {
            case let d where d < 0: return Roots.none // No real roots
            
            case let d where d == 0: return .one((b + sqrt(d)) / (2 * a))
            
            case let d where d > 0: return .two(
                    (b - sqrt(d)) / (2 * a),
                    (b + sqrt(d)) / (2 * a)
                )
                
            default: fatalError("Unreachable")
        }
    }
}

extension QuadraticFunction: CustomStringConvertible {
    var description: String {
        "\(a)x² + \(b)x + \(c)"
    }
}

func prettyPrintSolution(of function: QuadraticFunction) {
    let solution = function.solve()
    
    switch solution {
        case .none: print("The equation \(function) has no real roots.")
        case .one(let r): print("The equation \(function) has one distinct root \(r).")
        case .two(let r1, let r2): print("The equation \(function) has two distinct roots \(r1) and \(r2).")
    }
}

let function1 = QuadraticFunction(a: 9.1, b: -1.1, c: 1.3)
prettyPrintSolution(of: function1)

let function2 = QuadraticFunction(a: 1, b: 0, c: 0)
prettyPrintSolution(of: function2)

let function3 = QuadraticFunction(a: 1, b: 0, c: -1)
prettyPrintSolution(of: function3)

结果:

The equation 9.1x² + -1.1x + 1.3 has no real roots.
The equation 1.0x² + 0.0x + 0.0 has one distinct root 0.0.
The equation 1.0x² + 0.0x + -1.0 has two distinct roots -1.0 and 1.0.

推荐阅读