簡體   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