当我输入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 ");
}
}
}
答案 0 :(得分:4)
试试这个:
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 ");
}
}
答案 1 :(得分:1)
您需要在代码中使用if
,else if
和else
。然后,只有控件将只执行一个循环,该条件首先变为true,并忽略其他else if
和else
循环。否则,条件测试将在所有if
循环中发生,并且在条件测试通过时执行循环语句,无论先前的循环语句是否已执行
答案 2 :(得分:1)
或许更详细的语法有助于明确这一点:
if discriminant > 0
then
print ...
end if
if discriminant == 0
then
print ...
else
print ...
end if
所以我希望你能看到,只有当判别式不为零且判别式的if语句>才会应用else部分。 0与第一个if语句无关。
因此,您应该按如下方式重写代码:
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 ");
}
有关详细说明,请参阅here。
答案 3 :(得分:1)
你使用两个if和一个else。在这种情况下,首先检查第一个条件。然后下一个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 ");
}
}
}