所以我有这样的代码:
#include <iostream>
#include <string>
using namespace std;
#pragma region Class Definitions
struct Vector3
{
double x;
double y;
double z;
};
class Plane {
Vector3 point, normal, p_p1, p_p2, p_p3;
public:
Plane(Vector3 p1,
Vector3 p2, Vector3 p3);
const Vector3& get_point() const;
const Vector3& get_normal() const;
double get_hnf_d() const;
Vector3 closest_point(const Vector3& p);
double distance_to(const Vector3& p);
Vector3 intersect_line(const Line &l);
};
int main()
{
a.x = 1;
a.y = 2;
a.z = 3;
b.x = -1;
b.y = 2;
b.z = -2;
s = -2;
o.x = 0;
o.y = 0;
o.z = 0;
p1.x = sqrt(1 / 8);
p1.y = sqrt(1 / 8);
p1.z = sqrt(3 / 4);
p2.x = 0;
p2.y = 2 * sqrt(1 / 8);
p2.z = 0;
p3.x = sqrt(1 / 8) + sqrt(3 / 8);
p3.y = sqrt(1 / 8) + sqrt(3 / 8);
p3.z = sqrt(3 / 4) - sqrt(1 / 4);
q1.x = 1;
q1.y = 1;
q1.z = 1;
q2.x = -1;
q2.y = -1;
q2.z = -1;
switch (choice)
{
...
Plane _plane(p1, p2, p3);
cout << "Distance to p1, p2, p3 respectievly is : " << _plane.distance_to(p1) << endl;
}
return 0;
}
Plane::Plane(Vector3 p1, Vector3 p2, Vector3 p3)
{
p_p1 = p1;
p_p2 = p2;
p_p3 = p3;
}
const Vector3 & Plane::get_point() const
{
return p_p1;
}
const Vector3 & Plane::get_normal() const
{
return normalize(p_p2);
}
double Plane::get_hnf_d() const
{
Vector3 n, numerator;
double denominator;
numerator = cross_product(substract(p_p1, p_p3), substract(p_p2, p_p3));
denominator = sqrt(pow(numerator.x, 2) + pow(numerator.y, 2) + pow(numerator.z, 2));
cout <<"read" << numerator.y << numerator.x << denominator;
n.x = numerator.x / denominator;
n.y = numerator.y / denominator;
n.z = numerator.z / denominator;
//distance from origin
return -1 * dot_product(p_p1, n);
}
Vector3 Plane::closest_point(const Vector3 & p)
{
return Vector3();
}
double Plane::distance_to(const Vector3 & p)
{
return get_hnf_d() + dot_product(p, get_normal()) ;
}
我正在设置这样的值:
Plane::Plane(Vector3 p1, Vector3 p2, Vector3 p3)
{
p_p1 = p1;
p_p2 = p2;
p_p3 = p3;
}
然而,每当我尝试说print p_p1.x
时,我总是会返回值为0,从而导致我的计算失败。我哪里错了?我真的是一名C ++初学者。
感谢。
答案 0 :(得分:3)
你在行中进行整数除法:
p1.x = sqrt(1 / 8);
1/8在C ++中为0
在所有其他初始化中都是如此。
尝试写作
p1.x = sqrt(1.0 / 8.0);
答案 1 :(得分:0)
首先你必须在主p1和p2以及p3中声明并初始化它们然后将它们传递给plane的构造函数:
#include <iostream>
using namespace std;
#include <cmath>
struct Vector3
{
double x;
double y;
double z;
};
class Plane
{
Vector3 point, normal, p_p1, p_p2, p_p3;
public:
Plane(Vector3 p1,
Vector3 p2, Vector3 p3) : p_p1(p1), p_p2(p2), p_p3(p3){}
double distance_to(const Vector3& p)const;
};
double Plane:: distance_to(const Vector3& p)const
{
return get_hnf_d() + dot_product(p, get_normal()) ;
}
int main()
{
Vector3 p1 = {sqrt(1.0 / 8.0), sqrt(1.0 / 8.0), sqrt(3.0 / 4.0)};
// do the same thing as above
Vector3 p2, p3;
Plane _plane(p1, p2, p3);
cout << "Distance to p1 is : " << _plane.distance_to(p1) << endl;
return 0;
}
这只是一个非完整代码示例