I am teaching myself c++ and while on the topic of pointers, I came across an exercise which wants me to define a function length() that receives the coordinates of a point P passed as a pointer, and computes the distance from the origin to the point P:
double length(Coord3D *p);
int main()
{
Coord3D pointP = {10, 20, 30};
cout << length(&pointP) << endl; // would print 37.4166
}
class Coord3D // Given this class which had variables x,y,z.
{
public:
double x;
double y;
double z;
};
I am confused as to what my next steps are for example I am thinking I should use pointers to create a variable p
and set *p
to the class.
Also I think the function at the very top should contain the formula which would be sqrt(pow(x,2)+pow(y,2)+pow(z,3))
. If I am right then how can I implement the pointer properly and if I am wrong what I am I doing wrong and how can I fix it.
Please keep in mind this is my first time learning so I am trying my best.
The code that I wrote so far is :
#include<iostream>
#include<string>
#include<cmath>
using namespace std;
// Class
class Coord3D
{
public:
double x;
double y;
double z;
};
int p = Coord3D;
p*= Coord3D
// Function
double length(Coord3D *p)
{
double length = sqrt(pow(x,2)+pow(y,2)+pow(z,3));
cin>>x;
cin>>y;
cin>>z;
cout << length << endl;
}
// Main
int main()
{
Coord3D pointP = {10, 20, 30};
cout << length(&pointP) << endl; // would print 37.4166
}
Assuming the code works the output should a double that shows the distance from origin to point p.