Reference no: EM132209689
Write a program to determine the average momentum of a collection of items with random velocities and masses. Do this using the following outline:
1. Construct a function named randVec that will take no arguments and return a dynamically allocated 3-element array of doubles. Each element in the array should be a randomly generated value in the range -100.0 through +100.0.
2. Using randVec and your momentum function from the previous part, generate momentum vectors for 1000 items, each of which has a random velocity (as described above) and a randomly generated mass in the range 1.0 through 10.0. Save the momentum vectors using a suitable array of pointers.
3. Determine and display the average momentum vector of the items using a for loop. [Hint: the average should be done component by component.]
This is what the code look like. The only thing cannot do is No.3, determining the average momentum vector. You can modify this code or start a new one!
#include <iostream>
#include <bits/stdc++.h>
#include <string.h>
#include <ctime>
using namespace std;
double *momentum(double velocity[3], double mass)
{
double *arymntm = new double[3];
for (int i=0; i<3; i++)
{
arymntm[i] = velocity[i] * mass;
}
return arymntm;
}
double *randVec()
{
double *velVec = new double[3];
for (int i=0; i<3; i++)
{
velVec[i] = rand() %200+(-100);
}
return velVec;
}
int main()
{
double mass[1000];
double *velocity[1000][3];
double *res[1000],sum[1000];
for (int it=0;it<1000;it++)
{
mass[it]=(rand() % 10)+1;
*velocity[it]=randVec();
res[it]=momentum(*velocity[it],mass[it]);
cout<<"Momentum values:";
sum[it]=0;
for(int i=0; i<3; i++)
{
cout<<res[it][i]<<" ";
sum[it]=sum[it]+res[it][i];
}
cout<<"Average of Momentum "<<it+1<<" value is :"<<sum[it]/3<<endl;
}
// system("pause");
return 0;
}