C++阵列辅助

C++ array assistance

本文关键字:阵列 C++      更新时间:2023-10-16

我在单词 sum 中遇到错误,它说平均值 = 总和/ARRAY_SIZE;。据说这笔款项是未申报的。即使我之前在 getSum 函数中使用了 sum,我在这里只得到错误。我尝试将其声明为顶部的变量,但仍然收到该错误。我不知道如何以阻止此错误的方式声明它。

#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
// Function prototypes
int getHighest(int numbers[],int ARRAY_SIZE);
int getLowest(int numbers[],int ARRAY_SIZE);
int getSum(int numbers[],int ARRAY_SIZE);
int getAverage(int numbers[],int ARRAY_SIZE);

int main () {
// Variables
const int ARRAY_SIZE = 12; // Array size
int numbers [ARRAY_SIZE]; // Array with 12 integers
int count = 0; // loop counter variable
string filename;

//  Open file
cout << "Enter input filename:";
cin >> filename;
ifstream inputFile(filename);   // input file stream object
// Read numbers from file into array
while(count <ARRAY_SIZE && inputFile >> numbers[count])
count ++;
// Print results
cout<<ARRAY_SIZE<<" numbers read from input file."<<endl;
cout<<"The highest value is: "<<getHighest(numbers,ARRAY_SIZE)<<endl;
cout<<"The lowest value is: "<<getLowest(numbers,ARRAY_SIZE)<<endl;
cout<<"The sum of the numbers is: "<<getSum(numbers,ARRAY_SIZE)<<endl;
cout<<"The average of the numbers is: "<<getAverage(numbers,ARRAY_SIZE)<<endl;
}
int getHighest( const int numbers[], int ARRAY_SIZE)
{
int highest;
highest = numbers[0];
for(int count = 1 ; count < ARRAY_SIZE; count++)
{
if (numbers[count] > highest)
highest = numbers[count];
}
return highest;
}
int getLowest(const int numbers[], int ARRAY_SIZE)
{
int lowest;
lowest = numbers[0];
for (int count = 1; count < ARRAY_SIZE; count++)
{
if (numbers[count] < lowest)
lowest = numbers[count];
}
return lowest;
}
int getSum(const int numbers[], int ARRAY_SIZE)
{
int sum = 0;
for(int count = 0; count < ARRAY_SIZE; count++)
sum+= numbers[count];
return sum;
}
int getAverage(const int numbers[], int ARRAY_SIZE)
{
int average = 0;
for (int count = 0; count < ARRAY_SIZE; count++)
average = sum / ARRAY_SIZE;
return average;
}

这是说总和是未申报的。即使我之前在 getSum 函数中使用了 sum,我在这里只得到错误。

sum只是 getSum 中的一个局部变量,因此无法从getAverage访问它,事实上,当您离开getSum时,该变量不再存在

另请注意,getAverage中的for是无用的,因为您一直在执行其值始终相同的average = sum / ARRAY_SIZE;,因此您需要:

int getAverage(const int numbers[], int ARRAY_SIZE)
{
return getSum(numbers, ARRAY_SIZE) / ARRAY_SIZE;
}

请注意,您的声明和定义不对应,因为在您的定义中数组是const的,而不是在您的声明中。将数组也const在声明中:

int getHighest(const int numbers[],int ARRAY_SIZE);
int getLowest(const int numbers[],int ARRAYSIZE);
int getSum(const int numbers[],int SIZE);
int getAverage(const int numbers[],int SIZE);

也可以重命名ARRAY_SIZEsize以免与同名的全局变量混淆(即使它们收到其值(,并且SIZE重命名为size,因为大写通常不用于命名局部变量/参数。

除此之外,您处于C++,您是否确定要使用 (C( 数组而不是例如std::vector允许不为每个函数提供参数大小,并且还具有迭代器和预定义操作等?