Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        6年前关闭。
                                                                                            
                
        
我想制作一个二次方程式程序。我成功完成了基本操作,但有两个主要错误。一种是我尝试输入a,b或c十进制值时,另一种是我必须处理i(虚数)时。我该如何解决这些问题?我也很欣赏简化代码的方法,这是我的代码:

import java.util.Scanner;

public class Calculator {
    public static void main (String args[]){
    System.out.println("Input a");
    Scanner ai = new Scanner(System.in);
    double a = ai.nextInt();
    System.out.println("Input b");
    Scanner bi = new Scanner(System.in);
    double b = bi.nextInt();
    System.out.println("Input c");
    Scanner ci = new Scanner(System.in);
    double c = ci.nextInt();
    double Square1 = Math.pow(b, 2);
    double Square2 = -4*a*c;
    double Square3 = Square1 + Square2;
    double Square = Math.sqrt(Square3);
    double Bottom = 2*a;
    double Top1 = -b + Square;
    double x1 = Top1/Bottom;
    double Top2 = -b - Square;
    double x2 = Top2/Bottom;
    System.out.printf("X = %s", x1);
    System.out.printf("X = %s", x2);

    }
}

最佳答案

由于使用方法nextInt()而导致的第一个错误。当您尝试读取两次时,它会引发InputMismatchException-Method nextInt

而是使用nextNext方法来代替nextInt()。

第二个错误:Java不支持虚数:(

如果要使用虚数,则必须编写类ImaginaryNumber。

这是重构的代码:

import java.util.Scanner;

public class Calculator {
    public static void main(String args[]) {
        Scanner input = new Scanner(System.in);

        System.out.println("Input a");
        double a = input.nextDouble();

        System.out.println("Input b");
        double b = input.nextDouble();

        System.out.println("Input c");
        double c = input.nextDouble();

        double square1 = Math.pow(b, 2);
        double square2 = -4 * a * c;
        double square3 = square1 + square2;

        if (square3 < 0) {
            double square = Math.sqrt(square3);

            double bottom = 2 * a;
            double top1 = -b + square;
            double x1 = top1 / bottom;
            double top2 = -b - square;
            double x2 = top2 / bottom;

            System.out.printf("X = %s", x1);
            System.out.println();
            System.out.printf("X = %s", x2);
        } else {
            System.out
                    .println("Can not calculate square root for negative number");
        }

        input.close();

    }
}


您可以注意到我添加了

if (square3 < 0) {


那是因为Math.square方法只能取正数。
如果传递负数,它将返回NaN-不是数字:
Math.sqrt

10-08 17:52