Невозможно найти решение для «логической ошибки Java» в программе Quadratic Equation - PullRequest
1 голос
/ 20 октября 2011

Хотя программа работает отлично, мой профессор отметил, что следующее является логической ошибкой и должно быть исправлено. Я в тупике, разве нет только одного корня, когда дискриминант равен 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."); 
   }

 }
}

Ответы [ 4 ]

4 голосов
/ 20 октября 2011

Думайте об этом уравнении в терминах математики:

((-1*coefB) + Math.sqrt(discrim))/(2 * coefA);

Что происходит, когда coefA = 0?

4 голосов
/ 20 октября 2011

Единственная ошибка, которую я вижу, это то, что вам на самом деле не нужно делать:

 eq1root1 = ((-1*coefB) + Math.sqrt(discrim))/(2 * coefA);

Вы можете делать только

 eq1root1 = -1*coefB/(2 * coefA);

Так как вы внутри, если вызнайте, что дескриптор равен нулю.

Как уже упоминалось в другом комментарии, вам нужно убедиться, что coefA отличается от 0, так как это приведет к тому, что ваш код вызовет исключение (вы не можете разделить на 0).Хотя это на самом деле не будет квадратным уравнением, важно его проверить.

2 голосов
/ 20 октября 2011

Рассмотрим, что произойдет, если двойные числа не будут правильно представлять числа:

C:\Documents and Settings\glowcoder\My Documents>java Assignment6
Your coefficient  a = 1.0
Your coefficient  b = 0.2
Your coefficient  c = 0.01
This equation has two real roots.
Root 1 = -0.09999999868291098
Root 2 = -0.10000000131708903

Я построил этот пример с (x + .1)^2, который должен иметь 1 решение. Расширение x^2 + .2x + .01.

Вы также не обрабатываете, когда a = 0

C:\Documents and Settings\glowcoder\My Documents>java Assignment6
Your coefficient  a = 0.0
Your coefficient  b = 1.0
Your coefficient  c = 1.0
This equation has two real roots.
Root 1 = NaN
Root 2 = -Infinity
2 голосов
/ 20 октября 2011

Я могу только догадываться здесь ... То, что профессор вероятно пытался сказать, это то, что вы не можете использовать == для сравнения double с.

Например,

public static void main(String[] args) {
    double v = 0;
    for (int i = 0; i < 100; i++)
        v += 0.01;
    final double w = 1;
    System.out.println("v = " + v);
    System.out.println("w = " + w);
    if (v - w != 0.0) {
        System.out.println("difference: " + (v - w));
    }
}

напечатает следующее:

v = 1.0000000000000007
w = 1.0
difference: 6.661338147750939E-16
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...