Skip to content

Instantly share code, notes, and snippets.

@glamkawaii
Created November 13, 2012 10:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save glamkawaii/4065068 to your computer and use it in GitHub Desktop.
Save glamkawaii/4065068 to your computer and use it in GitHub Desktop.
Quadratic equation in Java
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