ios - 该等式将无法迅速解决此错误的原因
问题描述
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)
^~~~~
解决方案
您之前忘记了“让”,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.
推荐阅读
- sql-server - SQL Server:提高性能的文本搜索模式
- internationalization - 如何从相应的语言环境属性文件中加载所有属性
- c++ - std::set 与字符串键和潜在的效率损失
- python - 每 22 个字符向字符串添加一个输入,等到一个空格
- python - Discord.py - 使用命令更改前缀
- r - 如何在每行第一次出现匹配时停止匹配?
- tfs - 一旦设置了值,如何使 TFS 中的字段只读?
- c# - 当前线程调度程序创建在新 STA 线程上失败
- sql-server - 如何将 mod_authn_dbd 与 SQL Server (ODBC) 一起使用
- parsing - Flutter:通过 BottomNavigationBar 中的页面解析数据。错误:在初始化程序中只能访问静态成员