我们的OOP老师给我布置了一个作业。虽然我的代码看起来很好,但我仍然面临这个问题。
我必须从用户那里获取三角形顶点的坐标,并且必须判断它是否是一个r直角三角形。所以我简单地用毕达哥拉斯定理来求它,我们都知道用条件:h*h=b*b+p*p
但令人惊讶的是,这对某些特定的直角三角形不起作用。这里有一个这样的三角形:
顶点A:(x,y)=(1,3)
顶点B:(x,y)=(1,1)
顶点C:(x,y)=(5,1)
它计算得很完美,这是我通过打印计算出来的,但仍然不起作用。
然后尝试使用cmath
库中的sqrt()
函数:h=sqrt(b*b+p*p)
逻辑上是一样的,但它起作用了。
我想明白了,为什么早先的方法不管用?
下面是我的代码的简化版本:
#include <iostream>
#include <cmath>
using namespace std;
class Vertex {
double x, y;
public:
void take_input(char obj) {
cout << endl << " Taking Coordinates of Vertex " << obj << ": " << endl;
cout << " Enter the x component: ";
cin >> x;
cout << " Enter the y component: ";
cin >> y;
}
double distance(Vertex p) {
double dist = sqrt((x-p.x)*(x-p.x) + (y-p.y)*(y-p.y));
return dist;
}
};
class Triangle {
Vertex a, b, c;
public:
void take_inp(string obj) {
cout << endl << "Taking Vertices of the Triangle " << obj << ": " << endl;
cout << " Verteces should be in a counter clockwise order (as per convention)." << endl;
a.take_input('A');
b.take_input('B');
c.take_input('C');
}
void is_rt_ang() {
double h = a.distance(c)*a.distance(c);
double bp = a.distance(b)*a.distance(b) + b.distance(c)*b.distance(c);
/*
// Strangely this attempt works which is logically the same:
double h = a.distance(c);
double bp = sqrt(a.distance(b)*a.distance(b) + b.distance(c)*b.distance(c));
*/
if (h == bp) {
cout << "Angle is 90" << endl;
cout << h << " = " << bp << endl;
cout << "It is Right-Angled" << endl;
}
else {
cout << "Angle is not 90!" << endl;
cout << h << " != " << bp << endl;
cout << "It is Not a Right-Angled" << endl;
}
}
};
int main()
{
Triangle tri1, tri2;
tri1.take_inp("tri1");
tri1.is_rt_ang();
return 0;
}
在is_rt_ang
函数中,假设斜边始终是边ac
,但似乎没有做任何事情来验证这一点。
double h = a.distance(c)*a.distance(c);
double bp = a.distance(b)*a.distance(b) + b.distance(c)*b.distance(c);
您可以尝试先得到所有距离的平方,即(AC)^2
、(AB)^2
和(BC)^2
,然后从这三个距离中取最大值,找到斜边的候选值,然后执行如下操作:
bool isRightTriangle = max == (min1 + min2)
您还可能遇到浮点数的舍入错误。比较浮点数时,通常使用一个epsilon
值,因为浮点数固有的舍入错误。如果您不需要浮点值,可以使用整数,或者如果您确实需要浮点值,请尝试在您的等式中使用epsilon
值,如下所示:
abs(h - bp) <= epsilon
您应该能够在Web上找到更多关于浮点值、舍入错误和机器Epsilon的信息。