当我输入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 ");
}
}
你使用两个 if 和一个其他。在这种情况下,首先检查第一个条件。然后随着下一个if.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);
}
else if (discriminant == 0 ){
System.out.print("The root is " + root1);
}
else {
System.out.print("There are no real roots ");
}
}
}
你需要在代码中使用if
、else if
和else
。然后,只有控件将只执行一个条件首先变为 true 的循环,并忽略其他else if
和else
循环。否则,条件测试将在所有if
循环中发生,如果条件测试通过,则在循环中执行语句,无论先前的循环语句是否被执行<</p>
也许更详细的语法将有助于明确这一点:
if discriminant > 0
then
print ...
end if
if discriminant == 0
then
print ...
else
print ...
end if
所以我希望你能看到,只有当判别式不为零并且判别式> 0 的 if 语句独立于第一个 if 语句时,才会应用 else 部分。
因此,您应该按如下方式重写代码:
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 ");
}
有关更详细的说明,请参阅此处。