Created
November 13, 2012 10:26
-
-
Save glamkawaii/4065068 to your computer and use it in GitHub Desktop.
Quadratic equation in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package edu; | |
import static java.lang.System.out; | |
import java.lang.Math; | |
class SquareEquation { | |
public static void main(String[] args) { | |
out.print("Решим квадратное уравнение"); | |
if (args.length < 3) { | |
out.println("Введите параметры уравнения(a, b, c) в командной строке"); | |
return; | |
} | |
//Введем данные переменных a,b,c: | |
final int a = Integer.parseInt(args[0]); | |
final int b = Integer.parseInt(args[1]); | |
final int c = Integer.parseInt(args[2]); | |
out.print(a + "x^2 + " + b + "x + " + c + " = 0, a != 0: "); | |
//Найдем дискриминант: | |
int x, x1, x2; | |
final int discriminant = (b * b) - (4 * a * c); | |
//Вычислим корни: | |
String noRoots = "Нет корней"; | |
String oneRoot = " Уравнение имеет один корень: "; | |
String twoRoots = "Уравнение имеет два корня: "; | |
if (a == 0) { | |
out.println("a == 0"); | |
return; | |
} else if (b == 0 & c == 0) { | |
x = 0; | |
out.println(oneRoot + x); | |
return; | |
} else if (b == 0) { | |
x = -c / a; | |
if (x >= 0) { | |
x = (int) Math.sqrt(-c / a); | |
out.println(twoRoots + x + ", " + (-x)); | |
} else { | |
out.println(noRoots); | |
return; | |
} | |
} else if (c == 0) { | |
x1 = 0; | |
x2 = -(b / a); | |
out.println(twoRoots + x1 + ", " + x2); | |
} else if (discriminant < 0) { | |
out.println(noRoots); | |
return; | |
} else if (discriminant == 0) { | |
x = (int) ((-b + Math.sqrt(discriminant)) / 2 * a); | |
out.println(oneRoot + x); | |
} else if (discriminant > 0) { | |
x1 = (int) ((-b + Math.sqrt(discriminant)) / 2 * a); | |
x2 = (int) ((-b - Math.sqrt(discriminant)) / 2 * a); | |
out.println(twoRoots + x1 + ", " + x2); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment