我一直在研究这个程序,以确定是否可以通过三个用户输入的边长形成一个直角三角形。我的程序使用毕达哥拉斯定理,即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);
}
答案 0 :(得分:0)
你的逻辑错了。 如果至少有一个值^ 2是另外两个的值,则它是一个三角形。
在你的逻辑中,只有当所有三个值都是另外两个值的总和时才会到达else部分(只有当全部为0时才会发生)
答案 1 :(得分:0)
将您的状况检查更改为如下所示。检查if
块中的直角条件;否则显示错误消息。
bool IssideA = (sideA * sideA) == ((sideB * sideB) + (sideC * sideC));
bool IssideB = (sideB * sideB) == (sideC * sideC) + (sideA * sideA);
bool IssideC = (sideC * sideC) == (sideA * sideA) + (sideB * sideB);
if (IssideA || IssideB || IssideC)
{
JOptionPane.showMessageDialog(null, "Congratulations, those side lengths form a right triangle.","Right Triangle Tester", JOptionPane. INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(null,"I am sorry. Those side lengths do not form a right triangle.","Right Triangle Tester", JOptionPane.ERROR_MESSAGE);
}
答案 2 :(得分:0)
数学上,如果 2 + b 2 = c 2 ,则c必须大于a或b。如果你确定哪个长度是斜边,你的逻辑会简化,因为如果 2 + b 2 = c 2 ,那么a sup > 2 + b 2 + c 2 = 2 * c 2 ;你实际上不必知道哪个是哪个。
假设:
double a,b,c;
要确定三角形是否是直角,找到斜边并将平方和与斜边平方的两倍进行比较:
double h = a > b ? (a > c ? a : c) : (b > c ? b : c);
if (h * h * 2 == a * a + b * b + c * c)
// yes!
请注意,您可能会因double
类型的不精确而受到谴责。我建议将此代码转换为BigDecimal
以避免此问题。