|
|
|
One-Dimensional Array (Vector) Example -
Normalize a Vector
A normalized vevtor has length = 1.0
// normalized vector
#include<iostream>
using namespace std;
#include<cmath>
const int MAX = 20;
int main()
{
double V[MAX], W[MAX], norm;
int i, noEl;
cout << "Number of vector elements: ";
cin >> noEl;
cout << "Enter the elements:" << endl;
for(i=0; i < noEl; i++)
{
cin >> V[i];
}
// display vector V
cout << "Original vector V\n";
for(i=0; i < noEl; i++)
{
cout << V[i] << "
";
}
// calculate normalized vector
norm = 0.0;
for(i=0; i < noEl; i++)
{
norm += V[i]*V[i];
}
norm = sqrt( norm );
cout << "\nnorm = " << norm << endl;
for(i=0; i < noEl; i++)
{
W[i] = V[i] / norm;
}
// display vector W
cout << "Normalized vector W\n";
for(i=0; i < noEl; i++)
{
cout << W[i] << "
";
}
cout << endl;
return 0;
}
% g++ normal.cpp
% a.out
Number of vector elements: 5
Enter the elements:
2.3 4.6 -1.7 7.4 5.9
Original vector V
2.3 4.6 -1.7 7.4 5.9
norm = 10.9046
Normalized vector W
0.21092 0.421841 -0.155898 0.678614 0.541057
|
|