原題
http://www.codewars.com/kata/is-this-a-triangle/train/cpp
題目
Is this a triangle?
implement a method that accepts 3 integer values a, b, c. The method should return true if a triangle can be built with the sides of given length and false in any other case.
(In this case, all triangles must have surface greater than 0 to be accepted).
分析
三邊構(gòu)成三角形條件:任意兩邊之和大于第三邊,任意兩邊之差小于第三邊。
注意:int之和可能溢出
參考答案
namespace Triangle
{
bool isTriangle(int a, int b, int c)
{
long la(a),lb(b),lc(c);
return a>0 and b>0 and c>0 and
la-lb<lc and la-lc<lb and lb-lc<la and
la+lb>lc and la+lc>lb and lb+lc>la;
}
};
說明
本問題非常簡單,但是要注意參數(shù)的特殊情況。
- 負(fù)值和
0
值的情況,需要把這兩種情況排除。 - 參數(shù)是整型極大值的情況,兩個(gè)整型極大值會(huì)溢出。所以要把
int
轉(zhuǎn)long
其它
可以使用如下方式避免特殊情況。
bool isTriangle(int a, int b, int c){
return a-b<c and a-c<b and b-c<a;
}