Хотя программа работает отлично, мой профессор отметил, что следующее является логической ошибкой и должно быть исправлено. Я в тупике, разве нет только одного корня, когда дискриминант равен 0? Помощь будет по достоинству оценена!
Это код, который он упомянул:
if(discrim == 0)
{
eq1root1 = ((-1*coefB) + Math.sqrt(discrim))/(2 * coefA);
System.out.println("This equation only has a single real root. Root = " + eq1root1);
Вот полный код:
import java.lang.Math;
import javax.swing.JOptionPane;
public class Assignment6
{
public static void main(String[] args)
{
String a,
b,
c;
double coefA,
coefB,
coefC,
discrim,
eq1root1,
eq1root2;
//Here the user is inputting the coefficients through a popup dialog box
//Then the entered Strings are being converted to floating point numbers.
a = JOptionPane.showInputDialog( "Please enter a number for the quadratic coefficient a" );
coefA = Double.parseDouble (a);
b = JOptionPane.showInputDialog( "Please enter a number for the quadratic coefficient b" );
coefB = Double.parseDouble (b);
c = JOptionPane.showInputDialog( "Please enter a number for the quadratic coefficient c" );
coefC = Double.parseDouble (c);
//Here the coefficients that the user entered are being displayed.
System.out.println("Your coefficient a = " + coefA);
System.out.println("Your coefficient b = " + coefB);
System.out.println("Your coefficient c = " + coefC);
//The following "nested if" statement sorts out equations with only 1 root, 2 roots, and or no roots at all.
discrim = coefB*coefB - (4 * coefA * coefC);
if(discrim == 0)
{ eq1root1 = ((-1*coefB) + Math.sqrt(discrim))/(2 * coefA);
System.out.println("This equation only has a single real root. Root = " + eq1root1);
}
else if (discrim > 0)
{ eq1root1 = ((-1*coefB) + Math.sqrt(discrim))/(2 * coefA);
eq1root2 =((-1*coefB) - Math.sqrt(discrim))/(2 * coefA);
System.out.println("This equation has two real roots.");
System.out.println("Root 1 = " + eq1root1);
System.out.println("Root 2 = " + eq1root2);
}
else
{
System.out.println("This equation does not have any real roots.");
}
}
}