【发布时间】:2014-10-19 12:31:10
【问题描述】:
我一直在研究这个程序,以确定一个直角三角形是否可以由用户输入的三个边长组成。我的程序使用 勾股定理,即a2 + b2 = c2。当无法构建三角形时,我可以让程序重新识别,但我似乎无法让它识别何时可以构建。
有什么建议吗?我不确定这是我的if 语句的错误,还是简单的逻辑错误。 (我是编码的初学者,所以对于这个问题的简单性,我深表歉意)。
String myInputA = JOptionPane.showInputDialog(null, "Hello, and welcome to the 'Right' Triangle Tester.\nThis program will determine if three side lengths form a right triangle. \nPlease input the first side length below.","Right Triangle Tester",JOptionPane.INFORMATION_MESSAGE);
String myInputB = JOptionPane.showInputDialog(null, "Great. Please enter the second side below.","Right Triangle Tester", JOptionPane.INFORMATION_MESSAGE);
String myInputC = JOptionPane.showInputDialog(null, "Please enter the last side below.","Right Triangle Tester", JOptionPane.INFORMATION_MESSAGE);
double sideA = Double.parseDouble(myInputA);
double sideB = Double.parseDouble(myInputB);
double sideC = Double.parseDouble(myInputC);
if ((sideA * sideA) != ((sideB * sideB) + (sideC * sideC)))
{
JOptionPane.showMessageDialog(null,"I am sorry. Those side lengths do not form a right triangle.","Right Triangle Tester", JOptionPane.ERROR_MESSAGE);
}
else if ((sideB * sideB) != (sideC * sideC) + (sideA * sideA))
{
JOptionPane.showMessageDialog(null,"I am sorry. Those side lengths do not form a right triangle.","Right Triangle Tester", JOptionPane.ERROR_MESSAGE);
}
else if ((sideC * sideC) != (sideA * sideA) + (sideB * sideB))
{
JOptionPane.showMessageDialog(null,"I am sorry. Those side lengths do not form a right triangle.","Right Triangle Tester", JOptionPane.ERROR_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(null, "Congratulations, those side lengths form a right triangle.","Right Triangle Tester", JOptionPane. INFORMATION_MESSAGE);
}
【问题讨论】:
-
浮点运算只有一定的精度。根据您的输入值,您实际上可能永远不会遇到 a * a + b * b == c * c 的情况。它只是接近 c*c。尝试一下 Math.abs((a * a + b * b) - (c * c))
-
只有在之前的所有 if/else if 块都没有的情况下才会执行 else 块。你的逻辑是倒退的。你应该测试所有的可能性,如果没有一个导致直角三角形,那么并且只有这样,打印一个直角三角形是不可能的:如果 a2+b2 = c2 -> OK,否则如果 a2 + c2 == b2 -> OK else if b2 + c2 = a2 -> OK else -> not OK。请注意,您也可以先找到最大的数字,然后只进行一次测试。
标签: java if-statement logic