-1

我一生都无法弄清楚以下内容有什么问题,但是 findLargest 和 findSmallest(我相信还有 findAverage)函数无法正常工作并返回不正确的值。怎么了?

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int findLargest(int array[], int arraySize){
int largest = array[0]; //I set the largest to the first member of the array initially
for (int i = 0; i < arraySize; ++i){
    if (array[i] > largest){
        largest = i;
    }
}
return largest;
}

int findSmallest(int array[], int arraySize){
int smallest = array[0]; //I set the smallest to the first member of the array initially
for (int i = 0; i < arraySize; ++ i){
    if (array[i] < smallest){
        smallest = i;
    }
 }
return smallest;
}

int findAverage(int array[], int arraySize){
int total = 0;
for (int i = 0; i < arraySize; ++i){
    total += array[i];
}
int average = total/arraySize;

return average;
}

void display(int array[], int arraySize){

cout << "\nThe values for the array are: \n\n";

for (int i = 0; i < arraySize; ++i){
    cout << array[i] << endl;
   }
}



int main(){

const int size = 50;
int taker[size];
srand(time(NULL));

for (int i = 0; i < size; ++i){
    taker[i] = rand() % 100;  //generate 50 random numbers for the array taker
}

int largest = findLargest(taker, size);
int smallest = findSmallest(taker, size);
int average = findAverage(taker, size);

cout << "The largest entry was " << largest << endl;
cout << "The smallest entry was " << smallest << endl;
cout << "The average for all the entries is " << average << endl;

display(taker, size);

}
4

4 回答 4

2

如果你想返回索引。

int findLargest(int array[], int arraySize){
int largest = array[0]; //I set the largest to the first member of the array initially
int largestindex=0;
for (int i = 0; i < arraySize; ++i){
    if (array[i] > largest){
        largestindex=i;
        largest = array[i];
    }
}
return largestindex;
}

如果你想返回值。

int findLargest(int array[], int arraySize){
int largest = array[0]; //I set the largest to the first member of the array initially
for (int i = 0; i < arraySize; ++i){
    if (array[i] > largest){
        largest = array[i];
    }
}
return largest;
}
于 2013-06-30T02:06:09.403 回答
1

您的平均值函数看起来不错,但是,对于最大和最小,您需要使用索引处的值而不仅仅是索引。

最大的:

int findLargest(int array[], int arraySize){
   int largest = array[0]; //I set the largest to the first member of the array initially
   for (int i = 0; i < arraySize; ++i){
      if (array[i] > largest){
          largest = array[i];
      }
   }
    return largest;
}

最小:

int findSmallest(int array[], int arraySize){
    int smallest = array[0]; //I set the smallest to the first member of the array initially
    for (int i = 0; i < arraySize; ++ i){
        if (array[i] < smallest){
           smallest = array[i];
        }
    }
    return smallest;
}

您的平均功能看起来不错。

于 2013-06-30T02:07:12.400 回答
0

findLargest中,您设置largestiarray[i]

于 2013-06-30T02:06:13.673 回答
0

您应该smallest = array[i];largest=array[i];在各自的功能中进行设置。

于 2013-06-30T02:08:15.963 回答