Let's see if I can managed to do the same thing by using vector
inspite of arrays....
This is a possible implementation (new comments are identified by // @@ ).=
The structure of the code does not change a lot, but using std::vector
instead of raw C++ arrays helps a lot for debugging (e.g. catching array
index out of bounds), etc.
<code>
//////////////////////////////////////////////////////////////////////////=
#include <stdlib.h>
#include <time.h>
#include <iostream>
#include <fstream> // @@ Write to file
#include <vector> // @@ vector container
// @@
// I would not include all std namespace, but only classes I need
// using namespace std;
using std::cout;
using std::endl;
using std::ofstream;
// @@ array of doubles
typedef std::vector< double > DoubleArray;
// The function RandomNum creates random numbers
// in the range between small and big
// @@ use DoubleArray
void RandomNum(double small, double big ,int p, DoubleArray & array)
{
double range=(big-small)+1;
// @@ I used .at() method to be sure that array indexes
// are bounds-checked.
// If you need super-fast performance, you can still
// use operator[] (not bounds-checked, so less safe,
// but more fast).
for (int i=0; i<p; i++){
array.at(i)=small+int(range*rand()/(RAND_MAX + 1.0));
}
}
//the function AdditionArr Add the elements of an
//array and store the result in a number S
// @@ use const DoubleArray &, because it is read-only parameter
double AdditionArr (const DoubleArray & Arr,int k)
{
int i;
double Sum=0.0;
for (i=0; i<k; i++){
Sum+=Arr.at(i);
}
return Sum;
}
int main()
{
srand((unsigned)time(0));
int p=3;
int j;
double S;
// @@ a robust std::vector
DoubleArray array(3);
// *** Create output file
ofstream outFile;
outFile.open( "I:\\OutFile.txt" );
// @@ code modified to use DoubleArray
for(j=0;j<3;j++){
RandomNum(-1.5,1.5 ,p,array);
S = AdditionArr(array, p);
for (int k=0; k<p; k++){
cout << "array"<<"["<< k << "]" <<" = " << array=
otherwise I would have replied to your post earlier...
Thank you very much for the code.
that mine isn't so good as yours...