gpt4 book ai didi

java - 关于 IF 语句

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

当我输入 a、b、c 的值(即 1.0、3 1)时,答案应该仅为 ,表示根为 -0.381 和 -2.62803。我得到了两个答案,我也得到了“没有真正的根源”。我认为我使用 IF 语句的方式是错误的。请好心地向我解释我哪里出错了。

import java.util.Scanner;
public class sha {
public static void main(String[] args ){
Scanner input = new Scanner (System.in);

System.out.println("Enter a , b , and c : ");
double a = input.nextDouble();
double b = input.nextDouble();
double c = input.nextDouble();

// the equations
double discriminant = Math.pow (b , 2) - 4 * a * c;
double root1 = (-b + Math.sqrt(discriminant))/2 * a ;
double root2 = (-b - Math.sqrt(discriminant))/2 * a ;

if (discriminant > 0 ){
System.out.printf("The roots are %8.6f and %8.6f ", root1, root2);
}
if (discriminant == 0 ){
System.out.print("The root is " + root1);
}
else {
System.out.print("There are no real roots ");
}




}
}

最佳答案

试试这个:

if (discriminant > 0 ) {
System.out.printf("The roots are %8.6f and %8.6f ", root1, root2);
}
else if (discriminant == 0 ) {
System.out.print("The root is " + root1);
}
else {
System.out.print("There are no real roots ");
}

您的代码当前运行如下:

// first if group
if (discriminant > 0 ) {
System.out.printf("The roots are %8.6f and %8.6f ", root1, root2);
}

// second if group
if (discriminant == 0 ) {
System.out.print("The root is " + root1);
}
// handle everything else for second if group only
else {
System.out.print("There are no real roots ");
}

它应该这样运行:

// one if group
if (discriminant > 0 ) {
System.out.printf("The roots are %8.6f and %8.6f ", root1, root2);
}
else {
// second if condition in else statement
if (discriminant == 0 ) {
System.out.print("The root is " + root1);
}
// handle everything else
else {
System.out.print("There are no real roots ");
}
}

关于java - 关于 IF 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21153457/

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