gpt4 book ai didi

java - 获得二次方程的准确根

转载 作者:行者123 更新时间:2023-12-01 23:56:58 25 4
gpt4 key购买 nike

这是我迄今为止所拥有的代码。该项目的目标是让用户输入 a 的任意整数。 , b , c对于ax^2+bx+c方程。由于某种原因,我没有获得输入到程序中的任何数字的正确根。谁能指出我的错误行为吗?

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))

关于java - 获得二次方程的准确根,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15438627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com