A quadratic equation is an algebraic equation of the second degree. They are easy to solve if you know the quadratic formula.
Here is a simple function for calculating the real roots of a quadratic equation:
fun findRoots(a: Double, b: Double, c: Double) {
// the equation is ax^2 + bx + c = 0
val discriminant = b * b - 4 * a * c
when {
discriminant < 0.0 -> {
println("No real roots!")
}
discriminant == 0.0 -> {
val x = -b / (2 * a)
println("x = $x")
}
else -> {
val x1 = (-b + discriminant.pow(0.5)) / (2 * a)
val x2 = (-b - discriminant.pow(0.5)) / (2 * a)
println("x1 = $x1")
println("x2 = $x2")
}
}
}
If we decompose this code, we'll get the following functions:
fun calculateDiscriminant(a: Double, b: Double, c: Double): Double {
return b * b - 4 * a * c
}
fun calculateRoots(a: Double, b: Double, c: Double, discriminant: Double) {
val x1 = (-b + discriminant.pow(0.5)) / (2 * a)
val x2 = (-b - discriminant.pow(0.5)) / (2 * a)
if (x1 == x2) {
println("x = $x1")
} else {
println("x1 = $x1")
println("x2 = $x2")
}
}
What should the main function look like after decomposition? Make sure that the function produces the correct output and is properly decomposed (no unnecessary actions are performed).
Choose the option:
1)
fun main() {
val a = readln().toDouble()
val b = readln().toDouble()
val c = readln().toDouble()
val discriminant = calculateDiscriminant(a, b, c)
if (discriminant < 0.0) {
println("No real roots!")
} else if (discriminant == 0.0) {
calculateRoots(a, b, c, discriminant)
} else {
calculateRoots(a, b, c, discriminant)
}
}
2)
fun main() {
val a = readln().toDouble()
val b = readln().toDouble()
val c = readln().toDouble()
val discriminant = calculateDiscriminant(a, b, c)
calculateRoots(a, b, c, discriminant)
}
3)
fun main() {
val a = readln().toDouble()
val b = readln().toDouble()
val c = readln().toDouble()
val discriminant = calculateDiscriminant(a, b, c)
if (discriminant < 0.0) {
println("No real roots!")
} else {
calculateRoots(a, b, c, discriminant)
}
}