爪哇三角地区

时间:2012-04-24 00:45:52

标签: java area

根据我的家庭作业,我正在尝试构建一个计算三角形区域的应用程序。不太确定我哪里出错了,但我输入三角形的长度,并希望根据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;
    }
}

然后我有另一个主args的文件

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);
    }
}

2 个答案:

答案 0 :(得分:14)

1/2以整数运算计算,因此与所有整数除法一样,它被截断 - 在本例中为0。只需写下0.5即可。

答案 1 :(得分: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);
}

}