二次方程求解器无法在Java

时间:2015-07-15 23:21:30

标签: java quadratic

我有代码可以解决二次方程,但结果会产生NaN。

我现在环顾了两天,但找不到解决办法。任何和所有的建议将不仅仅是赞赏!

package quadratic;

import java.util.Scanner;

public class Formlua {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.println("enter value of A ");
        double a = input.nextDouble();
        System.out.println("enter value of B ");
        double b = input.nextDouble();
        System.out.println("enter value of C ");    
        double c = input.nextDouble();
        double four = 4;
        double square = Math.sqrt(b* b - 4 * a * c );

        double root1 = (-b + square) / (2*a);

        double root2 = (-b - square) / (2*a);   
        System.out.println("The answer is " + root1 + "and" + root2);

        System.out.println("Do you want to continue? y/n");

        String user = input.toString();
        if(user.equalsIgnoreCase("y"));
    }
}

2 个答案:

答案 0 :(得分:6)

此代码:

Math.sqrt(b* b - 4 * a * c );

可能会导致NaN(“不是数字”)。

如果b* b - 4 * a * c的值为负数,则只有复数的解(但不是双数据类型)

应该有一个条件

if (b* b - 4 * a * c<0) {
    System.out.println("There is no solution in real numbers");
    return;
}

答案 1 :(得分:3)

问题的最可能原因是Math.sqrt(b * b - 4 * a * c)。或者你的一个输入值是NaN(在这种情况下可能不是原因)。

有两种特殊情况: b * b&lt; 4 * a * c 和a = 0

如果b * b < 4 * a * c你的答案是在复杂的平面上(具体而言,不是实数)。 如果a = 0那么你实际上只有一个线性方程式。

您可以尝试以下代码:

package quadratic;
import java.util.Scanner;
public class Formlua {
  public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    System.out.println("enter value of A ");
    double a = input.nextDouble();

    System.out.println("enter value of B ");
    double b = input.nextDouble();

    System.out.println("enter value of C ");    
    double c = input.nextDouble();

    if (a == 0){
      // 0 = 0*x*x + b*x + c  ==> x = -c/b
      System.out.println("X = " + Double.toString(-c/b));
    } else {
      double inner = b * b - 4 * a * c;
      if (inner < 0){
        inner = -inner;
        inner = Math.sqrt(inner);
        System.out.println("X = " + Double.toString(-b) + " + " + Double.toString(inner) + "i")
        System.out.println("  = " + Double.toString(-b) + " - " + Double.toString(inner) + "i");
      } else {
         inner = Math.sqrt(inner);
           System.out.println("X = " + Double.toString(-b));
         if (inner == 0){
         } else {
           System.out.println("X = " + Double.toString(-b + inner));
           System.out.println("X = " + Double.toString(-b - inner));
      }
    }
  }
}

这可让您的用户输入任何双倍值并接收答案。