Kotlin

Program to Find all Roots of a Quadratic Equation | Kotlin

Program to Find all Roots of a Quadratic Equation | Kotlin

Program to Find all Roots of a Quadratic Equation | Kotlin

fun main(args: Array<String>) {

    val a = 5.9
    val b = 8
    val c = 3.9
    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)
}

 

Shibam Dhar

A sophomore web-dev freak always enthusiastic to learn more and explore different technologies and domains. Currently pursuing Bachelor of technology in CSE. Fascinated by web development. A hard worker and a self learner, who's goal is be a valuable asset. Always fascinated by communities and ready to contribute to it. I am always looking for opportunities enabling me to learn exciting technologies to boost my passion for programming.