Ejercicio :Pedir los coeficientes de una ecuación de 2º grado, y muestre sus soluciones reales. Si no existen, debe indicarlo.
Para realizar el ejercicio utilizamos la clase Entrada.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | package boletin1_1; import java.io.BufferedReader; import java.io.InputStreamReader; public class Entrada { // Constructor Entrada public Entrada(){ } public String inicializar(){ String buzon=""; InputStreamReader flujo=new InputStreamReader(System.in); BufferedReader teclado=new BufferedReader(flujo); try { // Control de Excepciones buzon=teclado.readLine(); } catch (Exception e){ System.out.append("Entrada incorrecta"); } return buzon; } public int entero(){ int valor=Integer.parseInt(inicializar()); return valor; } public double real(){ double valor=Double.parseDouble(inicializar()); return valor; } public String cadena(){ String valor=inicializar(); return valor; } public char caracter(){ String valor=inicializar(); return valor.charAt(0); } } |
Para resolver el problema utilizamos el siguiente código en el método main. Boletin1_1.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | package boletin1_1; public class Boletin1_1 { public static void main(String[] args) { double a,b,c; // coeficientes ax^2+bx+c=0 double x1,x2,d; // soluciones y determinante Entrada entrada = new Entrada(); System.out.println("Introduzca primer coeficiente (a):"); a=entrada.entero(); System.out.println("Introduzca segundo coeficiente (b):"); b=entrada.entero(); System.out.println("Introduzca tercer coeficiente (c):"); c=entrada.entero(); //calculamos el determinante d=((b*b)-4*a*c); if (d<0) { System.out.println("No existen soluciones reales"); } else { // queda confirmar que a sea distinto de 0. // si a=0 nos encontramos una división por cero. x1=(-b+Math.sqrt((d)))/(2*a); x2=(-b-Math.sqrt((d)))/(2*a); System.out.println("Solución: " + x1); System.out.println("Solución: " + x2); } } } |