-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvect.cpp
157 lines (137 loc) · 2.33 KB
/
vect.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#include <cmath>
#include "vect.h"
using namespace std;
namespace VECTOR
{
const double Rad_to_deg = 57.2957795130823;
//private methods
//calculates magnitude from x and y
void Vector::set_mag()
{
mag = sqrt(x*x + y*y);
}
void Vector::set_ang()
{
if ( x == 0.0 && y ==0.0 )
ang = 0.0;
else
ang = atan2(y,x);
}
//set x from polar coordinate
void Vector::set_x()
{
x = mag * cos(ang);
}
void Vector::set_y()
{
y = mag *sin(ang);
}
//public methods
Vector::Vector() //default constructor
{
x = y = mag = ang = 0;
mode ='r';
}
Vector::Vector(double n1, double n2, char form)
{
mode = form;
if ( form == 'r')
{
x = n1;
y = n2;
set_mag();
set_ang();
}
else if ( form == 'p')
{
mag = n1;
ang = n2/Rad_to_deg;
set_x();
set_y();
}
else
{
cout<<"Incorrect 3rd argument tp Vector()--";
cout<<"vector set to 0\n";
x = y = mag = ang = 0;
mode = 'r';
}
}
void Vector::set(double n1, double n2, char form)
{
mode = form;
if ( form == 'r')
{
x = n1;
y = n2;
set_mag();
set_ang();
}
else if(form == 'p')
{
mag = n1;
ang = n2/Rad_to_deg;
set_x();
set_y();
}
else
{
cout<<"Incorrect 3rd argument to vector\n";
cout<<"Vector set to 0\n";
x = y = mag = ang = 0.0;
mode = 'r';
}
}
Vector::~Vector() //destructor
{
}
void Vector::polar_mode()
{
mode = 'p';
}
void Vector::rect_mode()
{
mode = 'r';
}
//operator overloading
//add two vectors
Vector Vector::operator +(const Vector &b) const
{
Vector sum;
sum.x = x + b.xval();
sum.y = y + b.yval();
sum.set_ang();
sum.set_mag();
return (sum);
}
Vector Vector::operator -(const Vector &b)const
{
return (Vector(x-b.xval(),y-b.yval()));
}
//reverse sign of vector
Vector Vector::operator-() const
{
return (Vector(-x,-y));
}
Vector Vector::operator *(double n)const
{
return (Vector(n*x,n*y));
}
//friend methods
Vector operator*(double n, const Vector &a)
{
return (a*n);
}
//display rectangular coordinates if mode is r
//else diplay polar coordinate if mode is p
std::ostream &operator<<(std::ostream &os, const Vector &v)
{
if ( v.modeval() == 'r')
os<<"(x,y) = "<<v.xval()<<", "<<v.yval()<<endl;
else if (v.modeval() == 'p')
{
os <<"(m,a)= "<<v.magval()<<","<<v.angval()*Rad_to_deg<<endl;
}
return (os);
}
}