试图制作毕达哥拉斯定理代码,但它没有按计划运作

时间:2016-03-26 02:40:34

标签: java math

当我放入三角形的高度和底部时,我得到了NaN。例如,在下面的代码中,我有" hi"作为高度,b作为"基地"并且h为"斜边",如果我输入1作为基数,1作为高度,我得到NaN作为斜边。我如何拥有它是如果其中一方是未知的,那么用户将其设置为0,但由于某种原因它不起作用。我想知道我的代码中是否有错误?

注意:c.nextDouble()中的c是扫描仪名称。

double h = 0, b = 0, hi = 0;

System.out.println("Please enter in the sides as asked, if the unknown side is asked, then enter it as 0");

System.out.println("Enter the height of the triangle:");
hi = c.nextDouble();
System.out.println("Enter the base of the triangle: ");
b = c.nextDouble();
System.out.println("Enter the hypotenuse of the triangle: ");
h = c.nextDouble();

if (h != 0) {
    h = Math.sqrt((b * b) + (hi * hi));

    System.out.println("The hypotenuse side is:" + h);

} else if (hi != 0) {
    hi = Math.sqrt((h * h) - (b * b));

    System.out.println("The height is: " + hi);

} else if (b != 0) {
    b = Math.sqrt((h * h) - (hi * hi));

    System.out.println("The height is: " + b);
}

1 个答案:

答案 0 :(得分:1)

看起来你的if语句不正确。你有逻辑去"如果h不等于0,则设置为b ^ 2 - hi ^ 2。"这并不真正有意义,因为它们意味着其中一个值也将为零。

另外,你的输入有点偏。当你不接受按下回车的\ n时,Java会变得奇怪。只需添加c.nextLine();在每个c.nextDouble()

之后

示例输入抓取:

h = c.nextDouble();
c.nextLine(); //there is no need to store it anywhere. 

逻辑修复:

if (h == 0) {
    h = Math.sqrt((b * b) + (hi * hi));

    System.out.println("The hypotenuse side is:" + h);

} else if (hi == 0) {
    hi = Math.sqrt((h * h) - (b * b));

    System.out.println("The height is: " + hi);

} else if (b == 0) {
    b = Math.sqrt((h * h) - (hi * hi));

    System.out.println("The height is: " + b);
}   

}