数组函数无法正常工作(C ++)

时间:2013-06-30 02:02:38

标签: c++ arrays function

我不能为我的生活找出以下问题,但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 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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;
}

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

答案 2 :(得分:0)

findLargest中,您将largest设置为i而不是array[i]

答案 3 :(得分:0)

您应该在各自的职能中设置smallest = array[i];largest=array[i];