繁体   English   中英

我不知道如何找到这两个虚数

[英]I can't figure out how to find the two imaginary numbers

所以,我写了一个 Java 程序,它找到了一个二次方程的解,我的问题是我似乎无法编写正确的代码来找到“虚数”,当它打印出来时,我只得到“NaN”。 有什么解决办法吗?

import java.util.Scanner;
class Main {
  public static void main(String[] args) {
    
    Scanner scan = new Scanner(System.in);
    
    System.out.print("Enter the value for a: ");
    double a = scan.nextDouble();
    
    System.out.print("Enter the value for b: ");
    double b = scan.nextDouble();
    
    System.out.print("Enter the value for c: ");
    double c = scan.nextDouble();
    
    double result = b * b - 4.0 * a * c;
    
    if(result > 0.0){

      //to find two real solutions

      double x1 = (-b + Math.pow(result, 0.5)) / (2.0 * a);
      double x2 = (-b - Math.pow(result, 0.5)) / (2.0 * a);
      
      System.out.println("There are two real solutions.");
      System.out.println("x1 = " + x1);
      System.out.println("x2 = " + x2);
      
      //to find one real solution

    } else if(result == 0.0){
      double x1 = (-b / (2.0 * a));
      System.out.println("There is one real solution");
      System.out.println("x = " + x1);

      //to find the imaginary numbers

    } else if(result < 0.0){
      double x1 = (-b + Math.pow(result, 0.5)) / (2.0 * a);
      double x2 = (-b - Math.pow(result, 0.5)) / (2.0 * a);
      
      System.out.println("There are two imaginary solutions.");
      System.out.println("x1  = " + x1 + " + " + x2);
      System.out.println("x2  = " + x1 + " - " + x2);
    }
    
  }
}

在处理复杂的根时(当结果 < 0 时),您的代码中有几个不正确的地方:

  1. 您正在尝试评估result的平方根是否为负。 这将导致 NaN。 正确的方法是得到-result的平方根来得到你的答案。
  2. 您计算根的方式不正确。 两个根将具有相同的实部,即-b/(2*a)和相同的虚部值,仅符号不同。

我在下面修复了您的代码,以提供正确的 output。 计算实部,然后计算虚部。 然后用后缀“i”的虚部打印根来表示虚部。

double real = -b / (2*a);
double imag = Math.pow(-result, 0.5) / (2.0 * a);

System.out.println("There are two imaginary solutions.");
System.out.println("x1  = " + real + " + " + imag + "i");
System.out.println("x2  = " + real + " - " + imag + "i");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM