【问题标题】:I can't figure out how to find the two imaginary numbers我不知道如何找到这两个虚数
【发布时间】:2020-11-02 23:36:30
【问题描述】:

所以,我编写了一个 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);
    }
    
  }
}

【问题讨论】:

  • 你能添加一个你测试和预期输出的例子
  • 顺便说一句,没有必要将results 提高到 0.5 次方。有一个Math.sqrt 方法。

标签: java numbers quadratic quadratic-programming repl.it


【解决方案1】:

在处理复杂的根时(当结果

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

我在下面修复了您的代码以提供正确的输出。计算实部,然后计算虚部。根然后打印虚部,后缀“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");

【讨论】:

  • 必须是double real = -b / (2*a);,也可以在计算虚部时使用Math.sqrt函数。
  • 是的,正确,我忘记了正确的公式。更新了答案。
猜你喜欢
  • 1970-01-01
  • 2018-12-10
  • 2013-07-28
  • 1970-01-01
  • 2022-11-30
  • 2019-08-25
  • 1970-01-01
  • 1970-01-01
  • 2023-01-30
相关资源
最近更新 更多