6

根据我的家庭作业,我正在尝试构建一个计算三角形面积的应用程序。不太确定我哪里出错了,但我输入了三角形的长度,并希望根据 Heron 的公式显示正确的区域sqrt (s(s-a) (s-b) (s-c)):我得到的只是输出-0.0。这是代码:

import java.lang.Math;
public class Formula
{
    double area; double s;
    public double findArea(double sideA, double sideB, double sideC)
    { 
        s = 1/2 * (sideA + sideB + sideC);
        area = Math.sqrt(s*(s-sideA)*(s-sideB)*(s-sideC));
        System.out.println("The area of the triangle is " + area);
        return area;
    }
}

然后我有另一个主要参数的文件

import java.util.Scanner;

public class findTriangleArea {

    /**
     * @param args
     */

    public static void main(String[] args) {

        // TODO Auto-generated method stub
        Formula triangle = new Formula();
        double a,b,c;

        // input triangle lengths a, b, c 
        Scanner inputTriangle = new Scanner(System.in);
        System.out.println("Please enter triangle side a");
        a = inputTriangle.nextDouble();
        System.out.println("Please enter triangle side b");
        b = inputTriangle.nextDouble();
        System.out.println("Please enter triangle side c");
        c = inputTriangle.nextDouble();
        triangle.findArea(a, b, c);
    }
}
4

2 回答 2

14

1/2以整数算术计算,因此与所有整数除法一样,它被截断——在这种情况下,为0. 只要写0.5,你会没事的。

于 2012-04-24T00:48:11.517 回答
0

公共类 AreaOfTriangle {

public static void main(String[] args) {
    Scanner scanner=new Scanner(System.in);
    System.out.print("Enter the height: ");
    double height=scanner.nextDouble();
    
    System.out.print("Enter the base: ");
    double base=scanner.nextDouble();
    
    scanner.close();
    
    double area=(base*height)/2;
    
    System.out.println("---------------------------");
    System.out.println("Area of Triangle is: "+area);
}

}

于 2021-06-29T04:30:51.483 回答