我正在编写一个简单的程序来计算不等边三角形的面积。我们基本上必须先计算面积,然后输入 5 个答案并检查有多少是正确的。但是,每当我检查这些值时就会出现问题:
System.out.println("Enter the values of the three sides: ");
double a=sc.nextDouble();
double b=sc.nextDouble();
double c=sc.nextDouble();
double s=(a+b+c)/2.0;
double area=Math.sqrt(s*(s-a)*(s-b)*(s-c));
System.out.println("The area of the given triangle is="+area);
double ans[]=new double[5];
int count=0;
System.out.println("\nEnter the answers: ");
for(int i=0; i<5; i++)
{
ans[i]=sc.nextDouble();
if(ans[i]==area)
{
count++;
}
}
System.out.println(count+" students got the correct answer.");
但是,这是我得到的输出。
您面临的问题与Java中浮点数的比较有关。由于精度问题,== 可能无法按预期工作。比较浮点数时需要使用容差或增量值。
public class TriangleAreaCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the values of the three sides: ");
double a = sc.nextDouble();
double b = sc.nextDouble();
double c = sc.nextDouble();
double s = (a + b + c) / 2.0;
double area = Math.sqrt(s * (s - a) * (s - b) * (s - c));
System.out.println("The area of the given triangle is = " + area);
double ans[] = new double[5];
int count = 0;
double delta = 1e-6; // Adjust this value based on the desired precision
System.out.println("\nEnter the answers: ");
for (int i = 0; i < 5; i++) {
ans[i] = sc.nextDouble();
if (Math.abs(ans[i] - area) < delta) {
count++;
}
}
System.out.println(count + " students got the correct answer.");
}
}