6

我正在尝试检查 3 个边是否在 C++ 中形成一个三角形,但是我尝试过的所有可能数字的答案都说错了......

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    int a, b, c;

    cin >> a >> b >> c;

    if (pow(a,2) == pow(b,2) * pow(c,2) || pow(b,2) == pow(a,2) * pow(c,2) || pow(c,2) == pow(a,2) * pow(b,2))
        cout << "The sides form a triangle" << endl;
    else
        cout << "The sides do not form a triangle." << endl;
    return 0;
}
4

6 回答 6

18

假设a,b,c是三角形的边。因此,它必须满足这个标准:

  1. a + b > c
  2. a + c > b
  3. b + c > a

所有标准都必须为真。如果其中一个为假,则 a、b、c 将不会创建三角形。

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    int a, b, c;
    cin >> a >> b >> c;
    // check whether a, b, c can form a triangle
    if (a+b > c && a+c > b && b+c > a)
        cout << "The sides form a triangle" << endl;
    else
        cout << "The sides do not form a triangle." << endl;
    return 0;
}
于 2013-11-07T11:54:03.797 回答
3

要检查的三角形条件,

(a + b > c),
(b + c > a),
(c + a > b)
于 2013-11-07T11:58:24.117 回答
2

对于普通三角形

1. sum of any two sides is greater than third side (or)
2. difference of any two sides is less than third side

hint :  a+b > c || ...

对于直角三角形

1) sum of the squares of two sides equals the square of the longest side

暗示:

Find the longest side of three sides, that is find longest number in the three..
square the remaining two nums, add them and equate it to square of longest number
于 2013-11-07T12:07:51.147 回答
1

假设您只测试直角三角形,那么使用的逻辑是 z^2 = x^2 + y+2 所以逻辑中有一个错误:

 if (pow(a,2) == pow(b,2) * pow(c,2) || pow(b,2) == pow(a,2) * pow(c,2) || pow(c,2) == pow(a,2) * pow(b,2))

这应该是:

 if (pow(a,2) == pow(b,2) + pow(c,2) || pow(b,2) == pow(a,2) + pow(c,2) || pow(c,2) == pow(a,2) + pow(b,2))

但即使进行了这种更改,由于测试浮点数的相等性,结果也可能是错误的。给出一个特定的函数来测试 2 个浮点数是否足够接近,因为您决定了一些容差,然后使用它进行比较。

如果您不想将您的方法仅限于直角三角形,那么您可能希望阅读三角形不等式。总之,三角形不等式只是说明三角形中任何一条边的长度必须小于其他两条边的总和。

于 2013-11-07T11:53:24.557 回答
0

一种有效的方法是对给定的边进行排序。如果给定整个数组并且询问给定数组元素是否形成三角形,这将是有效的。这可以应用于 n 个给定的边。但是,这也可以应用于 3 面。假设给定的数组是 b。在您的情况下,数组 b 的长度为 h=3。

sort(b,b+h);
for (int j=0;j<(h-2);j++){
    if (b[j]+b[j+1]>b[j+2])
    {
return true;
    }
}
else {
return false;
}
于 2018-03-12T14:06:55.417 回答
-1

实际上,给定任意三个边,您只需要检查一个条件:最长边,比如 c,小于两条较短边的总和,比如 a 和 b。那是,

if c < a+b {
   return true;
} else return false;

这就是三角不等式定理的本质。当它是三角形时,其他条件将是微不足道的,如果不是,则无关紧要。当然,关键是使用简单的排序算法对三个边进行排序以找到最长的边。代码中的假设是边已经排序,因此 c 是最长的。

于 2019-04-20T19:02:50.000 回答