The code:
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
|
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <climits>
#define SIZE 9
using namespace std;
/*
Develop a function that finds the greatest difference between two
consecutive elements stored in an array. Develop a 9 element array
of doubles to test your code. Print to the screen which two numbers
have the greatest difference as well as the value of the difference.
Finally include an overloaded version of the function that will work
if the array is composed of integers. Include your code used to test this
function.(hint: you can create temporary variables)
*/
double Random (double)
{
double i =rand () /20;
return i;
}
int main (void)
{
srand (time(NULL));
double sub = 0;
int max = INT_MIN;
double first = 0;
double next = 0;
double posi = 0;
double posnext = 0;
int i = 0; //counter
int j = 0;
double Diff [SIZE] = {Random (0),Random (1),Random (2),Random (3),Random (4),Random (5), Random (6),Random (7), Random (8)};
for (i = 0; i < SIZE ; i++)
{
first = Diff [i];
next = Diff [i+1];
sub = first - next;
if (sub > max)
{
max = sub;
posi = Diff [i];
posnext = Diff [i+1];
}
cout << Diff [i]<< '\t';
}
cout << endl;
cout << "Greatest difference between two consecutive ints " << posi << " & " << posnext << " : " << max << endl;
return 0;
}
|
With output:
6.846e+07 9.27981e+07 4.82664e+07 1.36067e+06 1.0552e+08 7.55702e+07 8.72133e+07 2.9506e+07 5.30898e+07
Greatest difference between two consecutive ints 8.72133e+07 & 2.9506e+07 : 57707348 |
The formatting is much better with just ints, but the question wants doubles, so that's what it gets. I could populate the array myself, with 3.25 and 4.67 or whatever, but the random array each time makes me happier. (Side question, is there a way to restrict the double type to a certain amount of decimal places? I'd like if the Random function would make 4.78's and 9.2's)
I also didn't use the hint at all. I know about
new
and
delete
but I haven't quite figured them out yet.
So the first question is solved; the code subtracts one element in the 1d matrix from the next, then compares the outcome to previous and chooses the largest, and then outputs the two numbers subtracted and the difference between the two.
The problem is with
next = Diff [i+1]
which is great until the last element of the array. Then the code tries to subtract from an index that doesn't exist.
Also, to answer the totality of the question, I clearly don't understand what overloading is or does. I feel like with the clumsiness of my code, I probably overload a lot, without knowing it, but that's not the point. I read
http://www.cplusplus.com/doc/tutorial/classes2/ but it's not really making too much sense.
As always, thanks for taking the time!