English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of Kotlin Examples
In this program, you will learn to find all the roots of a quadratic equation (depending on the determinant) and print them using format() in Kotlin.
The standard form of a quadratic equation is:
ax2 + bx + c = 0, where a, b, and c are real numbers, a ≠ 0
The b2-4ac is called the determinant of the quadratic equation. The determinant explains the nature of the roots.
If the determinant is greater than 0, then the roots are real and different.
If the determinant is equal to 0, then the roots are real and equal.
If the determinant is less than 0, then the roots are complex and different.
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 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 equal roots else if (determinant == 0.0) { root2 = -b / (2 * a) root1 = root2 output = "root1 = root2 = %.2f;".format(root1) } //If the root is not a real number 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) }
When running the program, the output is:
root1 = -0.87+1.30i and root2 = -0.87-1.30i
In the above program, the coefficients a, b, and c are set to2.3,4and5.6. Then, calculate the determinant as b2 - 4ac.
According to the value of the determinant, calculate the root according to the above formula. Note that we have already used the library functionMath.sqrt()To calculate the square root of a number.
Then use the standard library function format() to store the output to be printed in a string variable. Then use println() to output the printed output output .
Here is the equivalent Java code for the above program:Java Program for Finding All Roots of a Quadratic Equation