[英]Array functions not working properly (C++)
我一輩子都無法弄清楚以下內容出了什么問題,但是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);
}
如果您想返回索引。
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;
}
您的平均值函數看起來不錯,但是,對於最大和最小值,您需要使用索引處的值,而不僅僅是索引。
最大:
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;
}
您的平均功能看起來不錯。
在findLargest
,將largest
設置為i
而不是array[i]
您應該設置smallest = array[i];largest=array[i];
各自的功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.