题解 | #计算一元二次方程#

计算一元二次方程

http://www.nowcoder.com/practice/7da524bb452441b2af7e64545c38dc26

import java.util.Scanner;

// 注意:
// 1. 在计算结果为0 的时候,double会保留负号,所以在下面的代码中加了判断
// 2. 在输出结果实部和虚部的时候需要使用字符串
// 3. 在输出结果实部和虚部的时候需要注意加好和减号
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double d = 0d;
        while (sc.hasNext()) {
            double a = sc.nextDouble();
            double b = sc.nextDouble();
            double c = sc.nextDouble();
            if (a == 0) {
                System.out.println("Not quadratic equation");
            } else {
                d = b * b - 4 * a * c;
                if (d == 0) {
                    double x = -1 * b / (2 * a);
                    if (x == 0) {
                        System.out.printf("x1=x2=0.00");
                    } else {
                        System.out.printf("x1=x2=%.2f", x);
                    }
                } else if (d > 0) {
                    // (-b±根号下△)/2a
                    double x1 = (-1 * b + Math.sqrt(d)) / (2 * a);
                    double x2 = (-1 * b - Math.sqrt(d)) / (2 * a); ;
                    if (x1 <= x2) {
                        System.out.printf("x1=%.2f;x2=%.2f", x1, x2);
                    } else {
                        System.out.printf("x1=%.2f;x2=%.2f", x2, x1);
                    }
                } else {
                    double real = -1 * b / (2 * a);
                    double virtual = Math.sqrt(-1 * d) / (2 * a);
//                     System.out.println(real);
//                     System.out.println(virtual);
                    if (virtual > 0 ) {
                        System.out.printf("x1=%.2f-%.2fi;x2=%.2f+%.2fi", real, virtual, real, virtual);
                    } else {
                        System.out.printf("x1=%.2f%.2fi;x2=%.2f+%.2fi", real, virtual, real,
                                          virtual * -1);
                    }
                }
            }
            System.out.println();
        }
    }
}
全部评论

相关推荐

点赞 1 评论
分享
牛客网
牛客企业服务