java - 尝试编写毕达哥拉斯定理代码,但它没有按计划工作

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

最佳答案

您的 if 语句似乎不正确。你的逻辑是“如果 h 不等于 0,则将其设置为 b^2 - hi^2”。这实际上没有意义,因为它们意味着这些值之一也将为零。

另外,你的输入有点不对劲。当你不接受按 Enter 键时的\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);
}   

}

关于java - 尝试编写毕达哥拉斯定理代码,但它没有按计划工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36231033/

相关文章:

math - 根据约束对矩阵进行归一化

java - 如果图像大小大于堆大小,我的应用程序会崩溃

java - 尝试解析时,Excel 字段的值变为 3.0E9,我需要 3000000000

javascript - 将从数组中随机选择的相同颜色分​​配给具有相同类别的所有元素

python-2.7 - python中的复数到极坐标形式

java - 请再次帮助家庭作业。递归乘以偶数?

wpf - 缓动函数的数学公式(ElasticEase、CircleEase、BounceEase、BackEase、PowerEase)?

java - 直接自引用导致循环父类(super class)问题 JSON

java - PMD的 “Must Follow”规则有哪些?

java - Spring测试中事务性不起作用