儘管程序工作得很好,但我的教授提到以下是一個邏輯錯誤,應該修復。我很難過,當判別式等於0時,是不是隻有一個根?幫助將真正被讚賞!無法在二次方程程序中找到「java邏輯錯誤」的解決方案
這是他提到的代碼:
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.");
}
}
}
請標記功課 – alf
這是一個古老的評論,而只是一個供參考我們在消除作業標籤的過程中不處理。所以,如果你看到作業標籤的問題,請刪除它! :-) – corsiKa