首页 > 解决方案 > C++ 数组辅助

问题描述

我在 sum 一词中出现错误,它表示 average = 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;
}

标签: c++xcode

解决方案


据说这笔款项是未申报的。尽管我之前在 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允​​许不给每个函数的参数大小以及具有迭代器和预定义操作等吗?


推荐阅读