【深基3.习8】三角形分类 · 教师题解
【深基3.习8】三角形分类
解题思路
先升序排序三条边,记为 a≤b≤c。若 a+b≤c 则不能构成三角形;否则用 a²+b² 与 c² 比较角类型,再独立判断等腰、等边。
正确性说明
排序后只需检验两短边之和是否大于最长边。余弦定理给出三种角类型的平方关系;边相等条件直接决定等腰和等边。
易错点
无效三角形只输出 Not triangle 并结束;等边也属于等腰,两个标签都要输出。
复杂度
时间 O(1),空间 O(1)。
参考代码(C++11)
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
long long a[3];
cin >> a[0] >> a[1] >> a[2];
sort(a, a + 3);
if (a[0] + a[1] <= a[2]) {
cout << "Not triangle\n";
return 0;
}
long long s = a[0] * a[0] + a[1] * a[1], t = a[2] * a[2];
if (s == t)
cout << "Right triangle\n";
else if (s > t)
cout << "Acute triangle\n";
else
cout << "Obtuse triangle\n";
if (a[0] == a[1] || a[1] == a[2])
cout << "Isosceles triangle\n";
if (a[0] == a[2])
cout << "Equilateral triangle\n";
return 0;
}