So basically I created two classes for two vectors and got there norms. How would I approach using both classes to find the distance between both vectors in my main function ? I know I can use the friend function but we have not been taught that in class so I have to use the scope :: operator and constructor and destructors. I been trying different things but nothing works any ideas ? I am fairly new to c++.
#include <iostream>
#include <math.h>
#include <stdio.h>
using namespace std;
class Vector {
private:
float x;
float y;
float z;
public:
Vector(float xaxis, float yaxis, float zaxis)
{
x = xaxis;
y = yaxis;
z = zaxis;
}
float getx() { return x; }
float gety() { return y; }
float getz() { return z; }
float normVector()
{
float result = sqrt(pow(x, 2) + pow(y, 2) + pow(z, 2));
return result;
}
};
class Vectortwo {
private:
float x;
float y;
float z;
public:
Vectortwo(float xaxis, float yaxis, float zaxis)
{
x = xaxis;
y = yaxis;
z = zaxis;
}
float getx() { return x; }
float gety() { return y; }
float getz() { return z; }
float normVectortwo()
{
float result = sqrt(pow(x, 2) + pow(y, 2) + pow(z, 2));
return result;
}
};
int main()
{
Vector v(2, 2, 2);
v.getx();
v.gety();
v.getz();
v.normVector();
cout << " X axis" << v.getx() << endl;
cout << " Y axis" << v.gety() << endl;
cout << " Z axis" << v.getz() << endl;
cout << " The norm of our first vector " << v.normVector() << endl;
Vectortwo b(3, 3, 3);
b.getx();
b.gety();
b.getz();
b.normVectortwo();
cout << " X axis" << b.getx() << endl;
cout << " Y axis" << b.gety() << endl;
cout << " Z axis" << b.getz() << endl;
cout << " The norm of our first vector " << b.normVectortwo() << endl;
return 0;
}
I know I can use the friend function but we have not been taught that in class [...]
You can always use getx(), gety() and getz() directly to calculate the distance. Since this gets a bit tiresome to write more than once you can write a little function that wraps the calculation:
float distance(Vector v1, Vectortwo v2)
{
return sqrt(
pow(v1.getx() - v2.getx(), 2)
+ pow(v1.gety() - v2.gety(), 2)
+ pow(v1.getz() - v2.getz(), 2)
);
}
It has to be declared before main() (but after Vector and Vectortwo) and could be used like this:
cout << "The distance is " << distance(v, b) << " units." << endl;
Since you somehow declared to vector classes Vector and Vectortwo that are basically identical (apart from the name), you can also just remove Vectortwo and use Vector for both instances, v and b. That would simplify the code and both parameters of the distance() function could be of type Vector.
Related
I have been trying to print the points like The position of the point is (1,2) from using class, but I can't figure out a way to do it. I simply can't find a way to return two numbers like that, but the problem requires solution that way.
#include <iostream>
using namespace std;
class MyPoint{
public:
int x,y,radius;
MyPoint()
{
x=0;
y=0;
}
MyPoint(int x1,int y1)
{
x=x1;
y=y1;
}
int point_display()
{
char st=(x,y);
return st;
}
int getAdd()
{
return x+y;
}
};
int main()
{
MyPoint mypoint;
cin>>mypoint.x>>mypoint.y;
cout<<"The position of the point is "<<mypoint.point_display()<<endl;
cout<<"The sum of the coordinates is "<<mypoint.getAdd()<<endl;
return 0;
}
The usual solution to this is to provide an overload of operator << for class MyPoint to print the point.
Something like this:
#include <iostream>
using namespace std;
class MyPoint{
public:
int x,y,radius;
MyPoint()
{
x=0;
y=0;
}
MyPoint(int x1,int y1)
{
x=x1;
y=y1;
}
int getAdd()
{
return x+y;
}
friend ostream& operator << (ostream& os, const MyPoint& p);
};
ostream& operator << (ostream& os, const MyPoint& p)
{
os << p.x << ", " << p.y;
return os;
}
int main()
{
MyPoint mypoint { 1,2 };
cout<<"The position of the point is "<<mypoint<<endl;
cout<<"The sum of the coordinates is "<<mypoint.getAdd()<<endl;
return 0;
}
Output:
The position of the point is 1, 2
The sum of the coordinates is 3
Live demo
Your point_display could return a string composed of the 2 values:
std::string point_display()
{
return std::string{"("} + std::to_string(x)
+ "," + std::to_string(x) + ")";
}
Alternatively, as your question asks about returning 2 values, the function could return a pair:
std::pair<int,int> point_display ()
{
return {x,y};
}
and in main, you could do:
auto [x, y] = mypoint.point_display();
cout << "The position of the point is ("
<< x << "," << y << ")" << endl;
However, since the data members are public, you could just destructure the object and print out the values in main:
auto [x, y, radius] = mypoint;
cout << "The position of the point is ("
<< x << "," << y << ")" << endl;
If all you want to do is print the coordinates, you could have the method do it:
void point_display()
{
cout << "(" << x << ", " << y << ")";
}
...
cout<<"The position of the point is ";
mypoint.point_display();
cout << endl;
If you really want to return the coordinates, you could have separate accessors ("getters"):
int getX()
{
return x;
}
int getY()
{
return y;
}
or use references:
void getCoordinates(int &rx, int &ry)
{
rx = x;
ry = y;
}
...
int a, b;
mypoint.getCoordinates(a, b);
cout << a << " " << b << endl;
I am trying to convert different coordinate systems. From polar to rectangular and vice versa. My pol_to_rect()function is not working properly. It is giving very small values(~10^(-44)) after converting and also before converting. There might be some problem while using the sin() and cos() functions. The rect_to_pol() is working fine for positive values.
Edit - When I changed atan() to atan2() how can I incorporate other values of x and y.
#include <iostream>
#include <cmath>
using namespace std;
#define PI 3.1415926
class Polar; // Forward declaration
class Rectangular {
private:
float x, y;
public:
Rectangular() {} // default constructor
Rectangular(float mv_x, float mv_y) {
x = mv_x;
y = mv_y;
}
void showData() const;
Polar rect_to_pol();
float& get_x() {
return x;
}
float& get_y() {
return y;
}
};
void Rectangular::showData() const {
cout << "--Rectangular--" << endl;
cout << "x: " << x << "\t" <<"y: " << y << endl;
}
class Polar {
private:
float r;
float theta;
public:
Polar() {} // default constructor
Polar(float mv_r, float mv_theta) {
r = mv_r;
theta = mv_theta;
}
void showData();
Rectangular pol_to_rect();
float& get_r(){
return r;
}
float& get_theta() {
return theta;
}
};
void Polar::showData() {
cout << "--Polar--" << endl;
cout << "r:" << r << "\t" << "Theta(Radians):" << theta << endl;
}
Rectangular Polar::pol_to_rect() {
Rectangular temp;
temp.get_x() = r * cos(theta*(PI/180.0)); // in degrees
temp.get_y() = r * sin(theta*(PI/180.0));
return temp;
}
Polar Rectangular::rect_to_pol() {
Polar temp;
temp.get_r() = sqrt(pow(x, 2) + pow(y, 2));
temp.get_theta() = atan2(y, x);
return temp;
}
int main()
{
Rectangular r1(-1, -1), r2;
Polar p1(12.0, 30.0), p2;
r1.showData();
p2 = r1.rect_to_pol();
cout << "After Conversion (RECT TO POLAR)->" << endl;
p2.showData();
p1.showData();
r2 = p1.pol_to_rect();
cout << "After Conversion (POLAR TO RECT)" << endl;
r2.showData();
return 0;
}
If I have a vector like this:
struct vector3D {
float x;
float y;
float z;
};
vector3D aVector = { 3.4, 4.4, 9.3 }; // my vector
How can I cout the aVector to the console?
you can overload the insertion operator << to use for your objects:
struct vector3D {
float x;
float y;
float z;
friend ostream& operator<<(ostream& out, vector3D rhs){
out << "( " << rhs.x << ", " << rhs.y << ", " << rhs.z << " )" << endl;
return out;
}
};
now you can use cout to print your object values:
int main(){
vector3D v = {10, 20, 30};
cout << v << endl;
}
I am having issues displaying coordinates that are read into a class. This is my first time using classes so please be understanding!
Here is what I have so far:
#include <iostream>
using namespace std;
class Vector{
private:
float x;
float y;
public:
Vector(float f1, float f2)
{
x=f1;
y=f2;
}
Vector(){}
float display()
{
Vector v;
cout << "(" << v.x << "," << v.y << ")" << endl;
return 0;
}
};
int main()
{
Vector v1(0.5, 0.5);
cout << "v1 ";
v1.display();
system("pause");
return 0;
}
It prints
v1 (-1.07374e+008,-1.07374e+008)
Your problem is that you are not printing out the coordinates of the Vector you created in main() but a default created one in your function. Instead of
float display()
{
Vector v;
cout << "(" << v.x << "," << v.y << ")" << endl;
return 0;
}
You need
float display()
{
//Vector v; remove this
cout << "(" << x << "," << y << ")" << endl;
// no v.x no v.y
return 0;
}
I suggest you change the default constructor to
Vector() : x(0), y(0) {}
So it would have printed
v1 (0,0)
You should also change
Vector(float f1, float f2)
{
x=f1;
y=f2;
}
To
Vector(float f1, float f2) : x(f1), y(f2) {}
As it is a good habit to get into. This can save resources and CPU cycles when dealing with non POD types. For more information see Why should I prefer to use member initialization list?
the Vector v; line is a mistake. You are basically creating a new uninitialized vector instead of crating your own instance.
one correction would be:
int display()
{
cout << "(" << x << "," << y << ")" << endl;
return 0;
}
since x and y are member of this class
This is following the question I asked in this thread : Link error missing vtable
I defined a class 'function' and two others classes 'polynomial' and 'affine' that inherit from 'function'.
class function {
public:
function(){};
virtual function* clone()const=0;
virtual float operator()(float x)const=0; //gives the image of a number by the function
virtual function* derivative()const=0;
virtual float inverse(float y)const=0;
virtual ~function(){}
};
class polynomial : public function {
protected:
int degree;
private:
float *coefficient;
public:
polynomial(int d);
virtual~polynomial();
virtual function* clone()const;
int get_degree()const;
float operator[](int i)const; //reads coefficient number i
float& operator[](int i); //updates coefficient number i
virtual float operator()(float x)const;
virtual function* derivative()const;
virtual float inverse(float y)const;
};
class affine : public polynomial {
int a;
int b;
//ax+b
public:
affine(int d,float a_, float b_);
function* clone()const;
float operator()(float x)const;
function* derivative()const;
float inverse(float y)const;
~affine(){}
};
Method inverse in polyomial does not seem to work fine. It is based on the Newton method applied to the function x->f(x)-y for fixed y (the element for which we're computing the inverse) and the current polynomial f.
float polynomial::inverse(float y)const
{
int i=0;
float x0=1;
function* deriv=derivative();
float x1=x0+(y-operator()(x0))/(deriv->operator()(x0));
while(i<=100 && abs(x1-x0)>1e-5)
{
x0=x1;
x1=x0+(y-operator()(x0))/(deriv->operator()(x0));
i++;
}
if(abs(x1-x0)<=1e-5)
{
//delete deriv; //I get memory problems when I uncomment this line
return x1;
}
else
{
cout<<"Maximum iteration reached in polynomial method 'inverse'"<<endl;
//delete deriv; //same here
return -1;
}
}
double polynomial::operator()(double x)const
{
double value=0;
for(int i=0;i<=degree;i++) value+=coefficient[i]*pow(x,i);
return value;
}
polynomial* polynomial::derivative()const
{
if(degree==0)
{
return new affine(0,0,0);
}
polynomial* deriv=new polynomial(degree-1);
for(int i=0;i<degree;i++)
deriv[i]=(i+1)*coefficient[i+1];
return deriv;
}
I test this method with p:x->x^3 :
#include "function.h"
int main(int argc, const char * argv[])
{
polynomial p(3);
for(int i=0;i<=2;i++) p[i]=0;
p[3]=1;
cout<<"27^(1/3)="<<p.inverse(27);
return 0;
}
This script outputs 27^(1/3)=Maximum iteration reached in polynomial method 'inverse'
-1 even if I put 10,000 instead of 100. I've read some articles on the internet and it seems that it's a common way to compute the inverse.
the abs function prototype is: int abs(int)
So a test like abs(x1-x0)<=1e-5 won't behave as you expect; you compare a int with a float. In this case the float will be converted to int so it the same as abs(x1-x0)<=0
This is probably why you don't get the expected result - I suggest adding a few more printouts to get to the bottom of things.
Well, the problem was in method 'derivative'. Instead of using the 'operator[]' that I redefined, I used '->coefficient[]' and the main script worked fine for p.inverse(27) (only 14 iterations). I just replaced deriv[i]=(i+1)*coefficient[i+1]; with deriv->coefficient[i]=(i+1)*coefficient[i+1];
Check This Code :
#include<iostream>
#include<cmath>
#include<math.h>
using namespace std;
void c_equation(int choose, double x);
void Processes(double x, double fx1, double fdx1, int choose);
void main()
{
int choose,choose2;
double x;
system("color A");
cout << " " << endl;
cout << "=============================================================" << endl;
cout << "Choose Equation : " << endl;
cout << "_____________________________________" << endl;
cout << "1- x-2sin(x)" << endl;
cout << "2- x^2 + 10 cos(x)" << endl;
cout << "3- e^x - 3x^2" << endl;
cout << " " << endl;
cin >> choose;
cout << "If you have values press 1/ random press 2 :" << endl;
cin >> choose2;
if (choose2 == 1)
{
cout << " " << endl;
cout << "Enter Xo : " << endl;
cin >> x;
c_equation(choose, x);
}
else if (choose2 == 2)
{
x = rand() % 20;
cout << "Xo = " << x << endl;
c_equation(choose, x);
choose2 = NULL;
}
else
{
cout << "Worng Choice !! " << endl;
choose = NULL;
choose2 = NULL;
main();
}
}
void c_equation(int choose, double x)
{
double fx;
double fdx;
double fddx;
double result;
if (choose == 1)
{
fx = x - 2 * sin(x);
fdx = 1 - 2 * cos(x);
fddx = 2 * sin(x);
result = abs((fx * fddx) / pow(fdx, 2));
}
else if (choose == 2)
{
fx = pow(x, 2) + 10 * cos(x);
fdx = 2 * x - 10 * sin(x);
fddx = 2 - 10 * cos(x);
result = abs((fx * fddx) / pow(fdx, 2));
}
else if (choose == 3)
{
fx = exp(x) - 3 * pow(x, 2);
fdx = exp(x) - 6 * x;
fddx = exp(x) - 6;
result = abs((fx * fddx) / pow(fdx, 2));
}
else
{
cout << " " << endl;
}
//------------------------------------------------------------
if (result < 1)
{
cout << "True Equation :) " << endl;
Processes(x, fx, fdx , choose);
}
else
{
system("cls");
cout << "False Equation !!" << endl;
choose = NULL;
x = NULL;
main();
}
}
void Processes(double x, double fx, double fdx , int choose)
{
double xic;
for (int i = 0; i < 3; i++)
{
xic = x - (fx / fdx);
cout << " " << endl;
cout << "Xi = " << x << " " << "F(Xi) = " << fx << " " << " F'(Xi) = " << fdx << " " << " Xi+1 = " << xic << endl;
x = xic;
if (choose == 1)
{
fx = xic - 2 * sin(xic);
fdx = 1 - 2 * cos(xic);
}
else if (choose == 2)
{
fx = pow(xic, 2) + 10 * cos(xic);
fdx = 2 * xic - 10 * sin(xic);
}
else if (choose == 3)
{
fx = exp(xic) - 3 * pow(xic, 2);
fdx = exp(xic) - 6 * xic;
}
}
}