gpt4 book ai didi

java - 直角三角形计算返回0?

转载 作者:行者123 更新时间:2023-12-01 07:26:08 25 4
gpt4 key购买 nike

我不知道我在这里做错了什么。我刚刚写了一个类似的代码,运行得很好。一旦我掌握了如何使用扫描仪类。我正在开发一个程序,该程序获取直角三角形的高度和底边,然后计算周长、面积和斜边。但它为每个方法返回 0.0,我无法弄清楚我是否缺少某种语法,或者我是否真的搞乱了我的计算。有人可以指出我错误的正确方向吗?

    public class RightTriangle {

private double height;
private double base;
private final double hypotenuse = Math.sqrt(Math.pow(height, 2) + Math.pow(base, 2));

public RightTriangle(double triHeight, double triBase)
{
triHeight = height;
triBase = base;
}

public double getPerimeter()
{
double perimeter = height + base + hypotenuse;
return perimeter;
}

public double getArea()
{
double area = (height + base) / 2;
return area;
}

public double getHypotenuse()
{
return hypotenuse;
}
}

这是我的主要方法:

    import java.util.Scanner;

public class CalculateTriangle
{

public static void main(String[] args)
{
Scanner triangleHeight = new Scanner(System.in);
System.out.print("Enter Triangle Height: ");
double height = triangleHeight.nextDouble();

Scanner triangleBase = new Scanner(System.in);
System.out.print("Enter Triangle Base: ");
double base = triangleBase.nextDouble();

RightTriangle newTriangle = new RightTriangle(height, base);

newTriangle.getPerimeter();
double perimeter = newTriangle.getPerimeter();

newTriangle.getArea();
double area = newTriangle.getArea();

newTriangle.getHypotenuse();
double hypotenuse = newTriangle.getHypotenuse();

System.out.println(perimeter);
System.out.println(area);
System.out.println(hypotenuse);

}
}

最佳答案

您的代码:

public RightTriangle(double triHeight, double triBase)
{
triHeight = height;
triBase = base;
}

应该是:

public RightTriangle(double triHeight, double triBase)
{
height = triHeight;
base = triBase;
}

关于java - 直角三角形计算返回0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24430063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com