繁体   English   中英

Java的二次方公式放置

[英]Quadratic Formula placement for Java

我在NAN和Real roots放置上遇到麻烦。 这是我的结果的屏幕截图:

在此处输入图片说明

这就是我想要做的:

  • 提示用户输入二次方程式的系数并以标准形式打印出方程式:ax ^ 2 + bx + c = 0(2 pts)

  • 计算方程的根。 如果a=0 ,则显示一条消息,指出该方程式不是有效的二次方程式。 否则,根据二次公式的判别式计算根。

  • 当判别为非负数时,请打印出真实的根。 注意:首先打印较小的根。 当判别为负时,分别计算复杂根的实部和虚部,然后以标准复杂“ a + bi”形式打印根。 注意:首先打印带有+ bi的复数根。 (8分)

     public class Quadratic { public static void main(String[] args) { java.util.Scanner input = new java.util.Scanner(System.in); double a = input.nextDouble(); double b = input.nextDouble(); double c = input.nextDouble(); double discriminant = Math.pow(b, 2) - 4 * a * c; System.out.println("a:"); System.out.println("b:"); System.out.println("c:"); System.out.println("Equation: " + a + "x^2+" + b + "x+" + c + "=0"); //If a=0, print a message indicating the equation is not a valid quadratic equation. if (a == 0) { System.out.println("Invalid quadratic equation."); } //When the discriminant is non-negative, print out the real root(s). if (discriminant > 0) { System.out.println("Real root(s):"); double root1 = (-b + Math.pow(discriminant, 0.5)) / (2 * a); double root2 = (-b - Math.pow(discriminant, 0.5)) / (2 * a); System.out.println("x = " + root2); System.out.println("x = " + root1); } //When the discriminant is negative, calculate the real and imaginary parts of the complex roots separately. if (discriminant < 0) { System.out.println("Complex roots:"); double r1 = -b/(2*a); double r2 = Math.sqrt(-discriminant)/(2*a); System.out.println("x = " + r1 + "+" + r2 + "i"); System.out.println("x = " + r1 + "-" + r2 + "i"); } } } 

当满足以下条件时使用else ,并且非负数应包括0,例如:

if (a == 0) {
    System.out.println("Invalid quadratic equation.");
} else if (discriminant >= 0) { // non-negative
    System.out.println("Real root(s):");
    ...
} else  {
    System.out.println("Complex roots:");
        ...

第一个问题 :即使方程不是二次方程( a == 0 ),您仍然要计算和显示根;

第二个问题 :通过使discriminant < 0表示复数根,而discriminant > 0表示实根,排除了discriminant == 0的情况。

处理这两个问题的正确逻辑是:

if (a == 0) {
    // it's not a quadratic: give message 
} 
else {
    if (discriminant < 0) {
        // compute and display complex roots
    } 
    else { // disciminant is zero or greater...
        // compute and display real roots
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM