我究竟做错了什么?我一直得到 NaN? (苍鹭公式)
What am I doing wrong? I keep getting NaN? (Heron's formula)
问题:
Write a program that reads the lengths of the sides of a triangle from the user. Compare the area of the triangle using Heron's formula, in which s represents half of the perimeter of the triangle and a,b, and c represent the lengths of the three sides.
import java.util.Scanner;
public class AreaOfTriangle
{
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
final double NUM_ONE = 0.5;
int a, b, c;
double s, area;
System.out.print("Enter side a: ");
a = scan.nextInt();
System.out.print("Enter side b: ");
b = scan.nextInt();
System.out.print("Enter side c: ");
c = scan.nextInt();
s = NUM_ONE * (a + b + c);
area = Math.sqrt(s*(s-a)*(s-b)*(s-c));
System.out.println("\nThe area of the triangle = " + area);
}
}
公式是正确的,但 s*(s-a)*(s-b)*(s-c)
最终可能会出现非常轻微的负数,具体取决于输入(由于浮点不精确)。在那种情况下,您应该在取 sqrt
和 return 零之前对此进行测试。
Math.sqrt
对负数将 return NaN
.
因为在某些情况下,您的代码最终会在 sqrt 调用中得到一个负值:
a = 1;
b = 2;
c = 5;
s = NUM_ONE * (a + b + c);
这里 s = 4.0 然后你的 sqrt 参数是 4*3*2*-1 是负的
您应该使用 Math.sqrt(Math.abs(...)) 吗?
问题:
Write a program that reads the lengths of the sides of a triangle from the user. Compare the area of the triangle using Heron's formula, in which s represents half of the perimeter of the triangle and a,b, and c represent the lengths of the three sides.
import java.util.Scanner;
public class AreaOfTriangle
{
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
final double NUM_ONE = 0.5;
int a, b, c;
double s, area;
System.out.print("Enter side a: ");
a = scan.nextInt();
System.out.print("Enter side b: ");
b = scan.nextInt();
System.out.print("Enter side c: ");
c = scan.nextInt();
s = NUM_ONE * (a + b + c);
area = Math.sqrt(s*(s-a)*(s-b)*(s-c));
System.out.println("\nThe area of the triangle = " + area);
}
}
公式是正确的,但 s*(s-a)*(s-b)*(s-c)
最终可能会出现非常轻微的负数,具体取决于输入(由于浮点不精确)。在那种情况下,您应该在取 sqrt
和 return 零之前对此进行测试。
Math.sqrt
对负数将 return NaN
.
因为在某些情况下,您的代码最终会在 sqrt 调用中得到一个负值:
a = 1;
b = 2;
c = 5;
s = NUM_ONE * (a + b + c);
这里 s = 4.0 然后你的 sqrt 参数是 4*3*2*-1 是负的
您应该使用 Math.sqrt(Math.abs(...)) 吗?