gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:11:47 27 4
gpt4 key购买 nike

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

封装区;

导入java.util.;导入java.text。;

公共(public)类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();
}

}

最佳答案

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

关于java - 即使在转换和扫描 nextDouble 后也不是数字错误。 (Java)请帮忙?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21816246/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com