Skip to content

Instantly share code, notes, and snippets.

@viktorsml
Created April 28, 2020 03:09
Show Gist options
  • Save viktorsml/f9b15221b9db4dd2123d74501660a774 to your computer and use it in GitHub Desktop.
Save viktorsml/f9b15221b9db4dd2123d74501660a774 to your computer and use it in GitHub Desktop.
import java.util.Scanner;
class FormulaGeneral {
static Scanner sn = new Scanner(System.in);
private static double askNumber(String question) {
double userInput = 0;
while (true) {
System.out.print(question);
try {
userInput = Double.parseDouble(sn.next());
break; // will only get to here if input was a double
} catch (NumberFormatException ignore) {
System.out.print("Intenta de nuevo. ");
}
}
return userInput;
}
public static void main(String[] args) {
// obtenemos los valores de los coeficientes
double a = askNumber("Ingresa el coeficiente a: ");
double b = askNumber("Ingresa el coeficiente b: ");
double c = askNumber("Ingresa el coeficiente c: ");
// resolvemos la raiz y revisamos si la solución es un numero real
double insideSquareRoot = Math.pow(b, 2) - (4 * a * c);
if (insideSquareRoot < 0) {
System.out.println("La solución no es real.");
} else {
double x1 = ((-b + Math.sqrt(insideSquareRoot)) / (2 * a));
double x2 = ((-b - Math.sqrt(insideSquareRoot)) / (2 * a));
System.out.println(String.format("El valor de x1 es: %s, el valor de x2 %s.", x1, x2));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment