我的英語說得不是很好,對不起。我在做一道練習題時遇到了問題。我被要求寫一段代碼,根據三維空間中兩點的x、y和z坐標找到它們之間的距離。但在做這個的時候,它要我使用類的結構,使用get-set函式,使用public和private的概念,并多載 "*"運算子來尋找距離。我寫了一段代碼,它給出了正確的結果,但它不符合預期的條件。如果你能幫助我,我將非常感激。非常感謝你。
#include<iostream>
#include<math.h>
using namespace std;
class coordinat
{
private:
int x1, y1, z1, x2, y2, z2;
public:
void get()
{
cout << "1.點X值。"。
cingt;> x1;
cout << "1.點Y值。"。
cingt;> y1。
cout << "1.點Z值。"。
cingt;> z1;
cout << "2.點X值。"。
cingt;> x2;
cout << "2.點Y值。"。
cin>> y2;
cout << "2.點Y值。"。
cingt;>z2。
}
void calculate()
{
float distance。
distance = sqrt(pow(x2 - x1, 2) pow(y2 - y1, 2) pow(z2 - z1, 2) )。
cout << "2點之間的距離。" << distance << endl;
}
};
int main()
{
coordinat c;
c.get()。
c.calculate()。
return 0;
uj5u.com熱心網友回復:
下面是完整的作業實體。注意使用double而不是int。
#include<iostream>
#include <tuple>
#include<math.h>
using namespace std;
class coordinate
{
private:
double x1, y1, z1;
public:
//this is a setter。
void set(double _x1, double _y1, double _z1)
{
x1 = _x1;
y1 = _y1;
z1 = _z1。
}
//這是個getter。
double get_x()
{
return x1;
}
double get_y()
{
return y1;
}
double get_z()
{
return z1;
}
//overload operator*
double operator*(坐標const &rhs)
{
return sqrt(pow(rhs. x1 - x1, 2) pow(rhs. y1 - y1, 2) pow(rhs.z1 - z1, 2) )。)
}
};
int main()
{
協調c1,c2。
//span>使用設定器
c1.set(7,0,2) 。
//使用getter。
std::cout<<"c1的x位置:"<<c1.get_x()<<std::endl。
std::cout<<"c1的y位置:"<<c1.get_y()<<std::endl。
std::cout<<"c1的z位置:"<<c1.get_z()<<std::endl。
//使用setter。
c2.set(2,6,0) 。
//使用getter。
std::cout<<"c2的x位置:"<<c2.get_x()<<std::endl。
std::cout<<"c2的y位置:"<<c2.get_y()<<std::endl。
std::cout<<"c2的z位置:"<<c2.get_z()<<std::endl。
//使用多載運算子*來計算距離。
double distance = c1*c2。
std::cout<<"兩點之間的距離是。"<<distance<<std::endl。
return 0。
uj5u.com熱心網友回復:
#include <cmath>notmath.h- 使
coordinat只存盤一個點(x,y,z)。 - 添加一個成員函式,用于將一個
坐標從另一個坐標中減去。coordinat& operator-=(const coordinat& rhs) { //加入代碼,從*this存盤的值中減去rhs的值。 return *this。 } - 添加一個成員函式來回傳
coordinat與origo的距離。?double lengthlength() const{ return std: :sqrt(x * x y * y z * z); } - 添加一個自由函式來減去兩個
coordinat的,回傳一個新的coordinat。coordinat operator-(const coordinat& lhs, const coordinat& rhs) { coordinatrv(lhs); /span> copy rv -= rhs; //使用成員函式 "operator-="。 return rv; }
通過這些補充,你可以要求用戶輸入資訊:
coordinat a, b;
std::cout << "輸入點1的資料。
"。
a.get()。
std::cout << "輸入點2的資料。
"。
b.get()。
并計算距離:
coordinat distance = a - b。
std::cout << distance.length()。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/328106.html
標籤:
