簡體   English   中英

獲取二次方程的精確根

[英]Getting accurate roots of quadratic equation

這是我到目前為止的代碼。 該項目的目標是讓用戶為ax^2+bx+c方程式的abc輸入任何整數。 由於某種原因,對於輸入到程序中的任何數字,我都得不到正確的詞根。 誰能指出我的錯誤做法?

import java.util.*;


public class Quad_Form {

public static void main(String[] args){

    Scanner sc = new Scanner(System.in);

    double a = 0;
    double b = 0;
    double c = 0;
    double discrim = 0;
    double d = 0;

    System.out.println("Enter value for 'a'");
    String str_a = sc.nextLine();
    a = Integer.parseInt(str_a);

    System.out.println("Enter value for 'b'");
    String str_b = sc.nextLine();
    b = Integer.parseInt(str_b);

    System.out.println("Enter value for 'c'");
    String str_c = sc.nextLine();
    c = Integer.parseInt(str_c);

    double x1 = 0, x2 = 0;
    discrim = (Math.pow(b, 2.0)) - (4 * a * c);
    d = Math.sqrt(discrim);

    if(discrim == 0){
        x1 = (-b + d) / (2* a);
        String root_1 = Double.toString(x1);
        System.out.println("There is one root at: " + root_1);
        }

    else {
        if (discrim > 0)
        x1 = (-b + d) / (2 * a);
        x2 = (-b - d) / (2 * a);
        String root_1 = Double.toString(x1);
        String root_2 = Double.toString(x2);
        System.out.println("There are two real roots at:"  + root_1 + "and"  + root_2);
        }

    if (discrim < 0){

        x1 = (-b + d) / (2 * a);
        x2 = (-b - d) / (2 * a);
        String root_1 = Double.toString(x1);
        String root_2 = Double.toString(x2);
        System.out.println("There are two imaginary roots at:" + root_1 + "and" + root_2);
        }
    }


}

@Smit對其中一個問題是正確的,但還有第二個問題。

discrim為負時, Math.sqrt(discrim)將不起作用。 您應該改為使用Math.sqrt(Math.abs(discrim))

abcd是double,您正在將它們解析為Integer。 因此,這可能是問題之一。

采用

 Double.parseDouble();

另一個問題是您不能使負數的平方根。 這將導致NaN 對於以下用途,但您應正確處理以得到准確的結果。

  Math.sqrt(Math.abs());

此外,您應該使用以下公式求根

根由二次方程式給出[

摘自Wikipedia 二次方程式

雙班

班級數學

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM