第三章第一题(代数:解一元二次方程)(Algebra: solve quadratic equations)
- *3.1(代数:解一元二次方程)可以使用下面的公式求一元二次方程两个根:
和
称作一元二次方程的判别式。如果它是正值,那么一元二次方程就有两个实数根。如果它为0,方程式就只有一个根。如果它是负值,方程式无实数根。
编写程序,提示用户输入a、b和c的值,并且显示基于判别式的结果。如果这个判别式为正,显示两个根。如果判别式为0,显示一个根。否则,显示“The equation has no real roots”(该方程式无实数根)。
注意,可以使用Math.pow(x,0.5) 来计算。
下面是一些运行示例:
Enter a, b, c:1.0 3 1
The equation has two roots -0.381966 and -2.61803
Enter a, b, c:1 2.0 1
The equation has one root -1.0
Enter a, b, c:1 2 3
The equation has no real roots
*3.1(Algebra: solve quadratic equations) The two roots of a quadratic equationcan be obtained using the following formula:
and
is called the discriminant of the quadratic equation. If it is positive, the equation has two real roots. If it is zero, the equation has one root. If it is negative, the equation has no real roots.
Note you can use Math.pow(x, 0.5) to compute.
Here are some simple runs:
Enter a, b, c:1.0 3 1
The equation has two roots -0.381966 and -2.61803
Enter a, b, c:1 2.0 1
The equation has one root -1.0
Enter a, b, c:1 2 3
The equation has no real roots
- 参考代码:
package chapter03;
import java.util.Scanner;
public class Code_01 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter a,b,c: ");
double a = input.nextDouble();
double b = input.nextDouble();
double c = input.nextDouble();
double discriminant = b * b - 4 * a * c;
if (discriminant > 0){
double answer1 = (-b + Math.pow(discriminant,0.5)) / (2 * a);
double answer2 = (-b - Math.pow(discriminant,0.5)) / (2 * a);
System.out.println("The equation has two roots " + answer1 + " and " + answer2);
}
else if (discriminant == 0){
double answer1 = (-b + Math.pow(discriminant,0.5)) / (2 * a);
System.out.println("The eqution has one root " + answer1);
}
else
System.out.println("The eqution has no real roots");
}
}
- 结果显示:
Enter a,b,c: 1 2.0 1
The eqution has one root -1.0
Process finished with exit code 0