如何使用 if-else 结构准确检查小数值?

问题描述 投票:0回答:1

我正在编写一个简单的程序来计算不等边三角形的面积。我们基本上必须先计算面积,然后输入 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 oop bluej
1个回答
0
投票

您面临的问题与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.");
}

}

© www.soinside.com 2019 - 2024. All rights reserved.