原文: https://www.programiz.com/kotlin-programming/examples/quadratic-roots-equation
二次方程的标准形式为:
ax2 + bx + c = 0, where
a, b and c are real numbers and
a ≠ 0
术语b<sup>2</sup>-4ac被称为二次方程的判别式。 判别式说明了根的性质。
- 如果判别式大于 0,则根是实数且不同。
- 如果判别式等于 0,则根是实数且相等。
- 如果判别式小于 0,则根是复数且不同。
fun main(args: Array<String>) {
val a = 2.3
val b = 4
val c = 5.6
val root1: Double
val root2: Double
val output: String
val determinant = b * b - 4.0 * a * c
// condition for real and different roots
if (determinant > 0) {
root1 = (-b + Math.sqrt(determinant)) / (2 * a)
root2 = (-b - Math.sqrt(determinant)) / (2 * a)
output = "root1 = %.2f and root2 = %.2f".format(root1, root2)
}
// Condition for real and equal roots
else if (determinant == 0.0) {
root2 = -b / (2 * a)
root1 = root2
output = "root1 = root2 = %.2f;".format(root1)
}
// If roots are not real
else {
val realPart = -b / (2 * a)
val imaginaryPart = Math.sqrt(-determinant) / (2 * a)
output = "root1 = %.2f+%.2fi and root2 = %.2f-%.2fi".format(realPart, imaginaryPart, realPart, imaginaryPart)
}
println(output)
}运行该程序时,输出为:
root1 = -0.87+1.30i and root2 = -0.87-1.30i在上述程序中,系数a,b和c分别设置为 2.3、4 和 5.6。 然后,将determinant计算为b ^ 2 - 4ac。
根据判别式的值,根的计算公式如上式所示。 注意,我们已经使用库函数Math.sqrt())计算数字的平方根。
然后使用 Kotlin 的标准库函数format()将要打印的输出存储在字符串变量output中。 然后使用println()打印输出。
以下是上述程序的等效 Java 代码:用于查找四级方程的所有根的 Java 程序