在C ++中确定等腰直角三角形

问题描述 投票:0回答:2

As you know

Isosceles Right Triangle具有直角三角形和等腰三角形特征。

例:

int a,b,c; //a,b and c are three triangle edge.
cout << "please insert a,b,c" << endl;
cin >> a;
cin >> b;
cin >> c;
if(a==b || b==c || c==a){
   cout << "isosceles triangle";
}
else if(a*a==b*b+c*c ||b*b==c*c+a*a || c*c==a*a+b*b)
{
   cout<<"right triangle");
} 

这就是我如何确定直角三角形和等腰三角形

为什么我不这样做

if(pow(a,2)==pow(b,2)+pow(c,2) ||pow(b,2)==pow(c,2)+pow(a,2) || pow(c,2)==pow(a,2)+pow(b,2)){
        if(a==b || b==c || c==a){
            cout << "isosceles right triangle";
        }
        else{
            cout << "right tri";
        }
 }

问题是:确定等腰直角三角形必须输入平方根数。

Isosceles Right Triangle

问题:当a = 1,b = 1,c = sqrt(2)

如何在C ++中将其确定为Isosceles Right Triangle

c++
2个回答
0
投票

根据Evg的评论,这是一个示例实现:

bool IsRightTriangle(double a, double b, double c)
{
    double max_allowed_error = 0.1;
    return (std::abs(a*a - b*b - c*c) <= max_allowed_error) || (std::abs(b*b - c*c - a*a) <= max_allowed_error) || (std::abs(c*c - a*a - b*b) <= max_allowed_error) ;
}

bool IsIsosceles(double a, double b, double c)
{
    return a == b || b == c || c == a;
}

int main()
{
    double a, b, c;
    cout << "\nEnter length of first side of the triangle ";
    cin >> a;
    cout << "\nEnter length of second side of the triangle ";
    cin >> b;
    cout << "\nEnter length of third side of the triangle ";
    cin >> c;    

    bool iso = IsIsosceles(a, b, c);
    bool rt = IsRightTriangle(a, b, c);

    if (iso && rt) std::cout << "\n Triangle is a Right Isosceles Triangle\n";
    else
        if (iso) std::cout << "\n Triangle is an Isosceles Triangle \n";
        else
            if (rt) std::cout << "\n Triangle is a Right Triangle \n";
}

1
投票

在你的例子中,所有边长abc都有int类型。没有等腰直角三角形可以具有所有整体边长。可能你应该使用floatdouble

如果您知道如何以数学方式进行测试,那么在代码中实现它应该非常简单。唯一要记住的是,由于舍入误差,在大多数情况下直接比较浮点数是没有意义的。

数学相等a2 = b2 + c2应该像这样检查:

std::abs(a*a - b*b - c*c) < EPSILON

其中EPSILON是一个小数,可以容忍浮点数的有限精度。

© www.soinside.com 2019 - 2024. All rights reserved.