Kotlin 查找二次方程所有根的程序

二次方程的标准形式是

ax2 + bx + c = 0, where
a, b and c are real numbers and
a ≠ 0

术语 b2-4ac 被称为一元二次方程的判别式。判别式决定了根的性质。

  • 如果判别式大于 0,则根是实数且不同。
  • 如果判别式等于 0,则根是实数且相等。
  • 如果判别式小于 0,则根是复数且不同。

示例:Kotlin 程序计算一元二次方程的根

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

在上面的程序中,系数 abc 分别设置为 2.3、4 和 5.6。然后,determinant 计算为 b2 - 4ac

根据判别式的值,根的计算方式如上公式所示。请注意,我们使用了库函数 Math.sqrt() 来计算数字的平方根。

要打印的输出存储在字符串变量 output 中,使用了 Kotlin 的标准库函数 format()。然后使用 println() 打印输出。


这是上面程序的等效 Java 代码: Java 程序计算一元二次方程的所有根

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战