In vector algebra we define a three dimensional vector v to be a on ordered trip
ID: 3856986 • Letter: I
Question
In vector algebra we define a three dimensional vector v to be a on ordered triple v = (x, y, z) where x, y and z are real numbers. We also define vector addition to be component wise this means that : If v = (s, t, u) and w = (x, y, z) then v + w = (s+x, t+y, u+z).
1. Create a new vector class in C++ that has a constructor that initializes its instances to (0, 0, 0).
2. Add a set Components function that will mutate (modify) the vector instance and set its components to the three parameters x, y, z passes to the function respectively.
3. Add a display function that displays the vector as triple (x, y, z).
4. Overload the + symbol to become vector addition.
5. Write a function called length() that returns the length of the vector as give by the formula:
length(v) = s2 + t2 + u2
meaning that the length is the square root of the sum of the components squared
6. Overload the rational == to yield true if v and w has the same length.
7. Write a main function that creates two instances and correctly add them display all three vectors and the length of the each vector.
Explanation / Answer
#include<iostream>
#include<cmath>
using namespace std;
class vector
{
double s, t, u;
public:
vector()
{
s = 0;
t = 0;
u = 0;
}
void set_vector(double x, double y, double z)
{
s = x;
t = y;
u = z;
}
void display()
{
cout << "(" << s << "," << t << "," << u << ")" << endl;
}
double length()
{
double result;
result = sqrt(s*s + t*t + u*u);
return result;
}
vector operator+(vector obj)
{
vector result;
result.s = s + obj.s;
result.t = t + obj.t;
result.u = u + obj.u;
return result;
}
bool operator==(vector obj)
{
if (s == obj.s && t == obj.t && u == obj.u)
return true;
else
return false;
}
};
int main()
{
vector v, w;
//set vector coordinates
v.set_vector(2, 4, 8);
w.set_vector(3, 9, 13);
//display vector v
cout << "v = ";
v.display();
//display vector w
cout << "w = ";
w.display();
cout << "Length of vector v = " << v.length() << endl;
cout << "Length of vector w = " << w.length() << endl;
//check vector addition
vector result = v + w;
cout << "Result of vector addtion = ";
result.display() ;
//check if vector are equal
if (v == w)
{
cout << "Two vectors v and w are equal" << endl;
}
else
{
cout << "Two vectors v and w are not equal " << endl;
}
}
--------------------------------------------------------------------------------------------------------------------------------
//output
v = (2,4,8)
w = (3,9,13)
Length of vector v = 9.16515
Length of vector w = 16.0935
Result of vector addtion = (5,13,21)
Two vectors v and w are not equal
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.