即使在转换和扫描nextDouble之后,也不是数字错误。 (Java)请帮帮忙?

时间:2014-02-16 20:38:08

标签: java double java.util.scanner

运行此程序时遇到问题。循环和计算工作正常。由于某种原因,它只计算50以下的区域。小数字运行正常,但较大的计算得到NaN结果,这是一个问题。有什么帮助吗?

包区;

import java.util。; import java.text。;

公共类AreaPtTwo {

//this creates a scanner object for the user to input through
final static Scanner sc = new Scanner(System.in);


public static void main (String[] args){
    boolean playAgain = true;
    DecimalFormat fmt = new DecimalFormat("#.###");
    while(playAgain){
        //gets the three inputs from the user
        double a = getNum(1);
        double b = getNum(2);        
        double c = getNum(3);

        // calculates 's' = perimeter/2
        double s = (a+b+c)/2.0;

        //this calculates the area of the triangle by getting the square root of (s(s-a)(s-b)(s-c)) --> this is hard to read but there isn't really a better way to put it in comments.
        double area = (double) Math.sqrt(s*(s-a)*(s-b)*(s-c));

        System.out.println("Area: " + fmt.format(area));

        //Closes 
        System.out.println("_______________________________________________________________________________________________________");
        System.out.println("Play again? (y/n)");
        String again = sc.next();
        if(again.charAt(0) == 'y') playAgain = true;
        else if (again.charAt(0) == 'n') playAgain = false;
        else playAgain = false;
    }
}

// this method is to get the input from the user. It is in a method because it is performed three times. this will only accept numbers, no strings or characers allowed
public static double getNum(int n){
    System.out.println("Enter the length of side " + n +":");

    // this will loop until to make sure that the user does not enter characters or words, and will prompt the user until a number is entered
    while (!sc.hasNextDouble()){
        System.out.println("Invalid input\nEnter the length of side " + n +":");
        sc.next(); // this has to be sc.next() because it will throw a hige error if someone enters a word
    }

    // this returns the next double entered as the variable. 
    return sc.nextDouble();
}

}

2 个答案:

答案 0 :(得分:1)

您的Math.sqrt()功能获得了负值,请尝试重新分析您的s*(s-a)*(s-b)*(s-c)区域 - 任何负值都会返回NaN

答案 1 :(得分:1)

数学上,如果边不能构成实际的三角形,则s(s-a)(s-b)(s-c)应为负,并且负的平方根返回Nan。看来,当你得到一个NaN时,问题在于几何,而不是编程。对于任何可形成实际三角形的数字,它都可以正常工作 如果您不知道我的意思,请尝试绘制长度为1,2和5的三角形。