Hi everyone. I have enclosed my sorting program and for some reason the average function is not averaging. I cannot find my mistake. The program sorts no problem at all but my average takes the smallest integer and uses it as the average. Can anyone take a looksee and tell me where my mistake is? Thanks!
Code://list.h #ifndef LIST_H_INCLUDED #define LIST_H_INCLUDED #include <iomanip> #include <iostream> using namespace std; #define MAX 100 bool isAscending (int *array, int len); bool isDescending (int *array, int len); bool isInOrder (int *array, int len); double average (const int *array, int len); int *findMax (const int *x, int n); int getInfo (int *array, int max); int total (const int *array, int len); void sort (int *x, int n); void swap (int &x, int &y); #endif // LIST_H_INCLUDED //main.cpp #include "list.h" int main() { int array[MAX]; int counter = 0; int len; len = getInfo (array, MAX); double x = average (array, len); if (len > 0) cout << "\nAvg: " << x << endl; for (;counter < len; counter++) cout << setw(4) << *(array + counter); cout << endl; if (isInOrder (array, len)) cout << "its in order" << endl; else sort (array, len); if (isInOrder (array, len)) cout << "its in order" << endl; for (counter = 0; counter < len; counter++) cout << setw(4) << *(array + counter); cout << endl; return 0; } //isAscending.cpp #include "list.h" bool isAscending (int *array, int len) { for (int counter = 0; counter < len - 1; counter++) if (*(array + counter) > *(array + counter + 1)) return false; return true; } //isDescending.cpp #include "list.h" bool isDescending (int *array, int len) { for (int counter = 0; counter < len - 1; counter++) if (*(array + counter) < *(array + counter +1)) return false; return true; } //isInOrder.cpp #include "list.h" bool isInOrder (int *array, int len) { return isAscending (array, len) || isDescending (array, len); } //average.cpp #include "list.h" double average (const int *array, int len) { int tot = total (array, len); return (double) tot/len; } //findMax.cpp #include "list.h" int *findMax (const int * x, int n) { int temp = 0; int counter = 1; while (counter <= n) { if (*(x + counter) > *(x + temp)) temp = counter; counter++; } return (const_cast < int *> (x + temp)); } //getInfo.cpp #include "list.h" int getInfo(int *array, int max) { int counter = 0; while (cin >> *array) { array++; counter++; if (counter == max) break; } return counter; } //total.cpp #include "list.h" int total (const int *array, int len) { int sum = 0; while (len--) sum +=*array; return sum; } //sort.cpp #include "list.h" void sort (int *x, int n) { int *j; while (n--) { j = findMax (x, n); swap (*j, *(x + n)); } } //swap.cpp #include "list.h" void swap(int &x,int &y) { int temp = x; x = y; y = temp; }



LinkBack URL
About LinkBacks



