我正在为一本学校的书做一些编程练习,该练习是关于确定用户输入的边是否指示它是直角三角形。
要弄清楚,您必须执行毕达哥拉斯定理,即a ^ 2 + b ^ 2 = c ^ 2。我写了一个if
语句,询问是否(side1 * side1)+(side2 * side2)=(side3 * side3),然后它是一个直角三角形,如果不是,我写了一个else
语句以打印它不是一个右三角形。下面是我编写的代码。
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main() {
int side1=0, side2=0, side3=0;
cout << "Enter the first side of the triangle: " << endl;
cin >> side1;
cout << "Enter the second side of the triangle: " << endl;
cin >> side2;
cout << "Enter the third side of the triangle: " << endl;
cin >> side3;
if ((side1 * side1) + (side2 * side2) == side3 * side3)
{
cout << "It is a right angled triangle" << endl;
exit(1);
}
else
{
cout << "It is not a right angled triangle" << endl;
exit(1);
}
return 0;
}
我不断从代码中得到的响应是,一切都是直角三角形,这是我不想要的。
您应按长度排序长度,因为C必须是毕达哥拉斯定理起作用的斜边(最长的一面)。在std :: array中收集您的整数,并使用std :: sort,如下所示:
#include <iostream>
#include <string>
#include <algorithm>
#include <array>
using namespace std;
int main(){
array<int,3> side;
cout << "Enter the first side of the triangle: " << endl;
cin >> side[0];
cout << "Enter the second side of the triangle: " << endl;
cin >> side[1];
cout << "Enter the third side of the triangle: " << endl;
cin >> side[2];
std::sort( begin(side), end(side) );
if ((side[0] * side[0]) + (side[1] * side[1]) == side[2] * side[2])
{
cout << "It is a right angled triangle" << endl;
}
else
{
cout << "It is not a right angled triangle" << endl;
}
return 0;
}
仅检查side [2]最长)不足以确定三角形是否为直角。您需要将方程式中最长的一面放在正确的位置。
首先,您不需要使用exit(1)
语句,因为程序已经在return语句中退出。而且您不需要使用括号,因为乘法运算已经比比较运算符(例如==
)享有更高的优先级。
其次,该代码似乎不错,但是可能存在编译器差异问题。您可以尝试其他代码:
注意:
我使用TDM-GCC,我希望这段代码也可以在大多数C ++编译器上使用。示例输出
Enter the first side: 5 Enter the second side: 12 Enter the third side: 13 It's really a triangle.