首页 > 解决方案 > “使用了未初始化的局部变量”

问题描述

我调用了 2 个函数,它们分别找到最高和最低等级。他们返回“highestGrade”和“lowestGrade”,但我很困惑为什么编译时会出现错误。这是一项实验室作业,大部分代码都是预先编写的,我的任务是填写缺失的代码。错误发生在第 55 行和第 63 行附近,我所指的函数位于代码的末尾。

我是使用数组的新手,所以我假设我可能在函数“findHighest”和“findLowest”中有一些错误代码。例如,“findHighest”中的程序将假定它遇到的第一个数组是最高等级的,并将剩余的数组与它进行比较,直到找到一个更高的数组。如果是,它将将该数组分配给“highestGrade”。

float findAverage(const GradeType, int);
int findHighest(const GradeType, int);
int findLowest(const GradeType, int);

int main()
{
    GradeType  grades;
    int  numberOfGrades;
    int pos;

    float avgOfGrades;
    int highestGrade;
    int lowestGrade;

    // Read in the values into the array
    pos = 0;
    cout << "Please input a grade from 1 to 100, (or -99 to stop)" << endl;
    cin >> grades[pos];
    int i = 1;

    while (grades[pos] != -99)
    {
        // read in more grades
        pos = i;
        cout << "Please input a grade from 1 to 100, (or -99 to stop)" << endl;
        cin >> grades[pos];
    }

    numberOfGrades = pos;  // Fill blank with appropriate identifier
                           // call to the function to find average
    findAverage(grades, numberOfGrades);
    avgOfGrades = findAverage(grades, numberOfGrades);
    cout << endl << "The average of all the grades is " << avgOfGrades << endl;

    //  Fill in the call to the function that calculates highest grade
    findHighest(grades, highestGrade);
    highestGrade = findHighest(grades, highestGrade);
    cout << endl << "The highest grade is " << highestGrade << endl;

    // Fill in the call to the function that calculates lowest grade
    findLowest(grades, lowestGrade);
    // Fill in code to write the lowest to the screen
    lowestGrade = findLowest(grades, lowestGrade);

    cout << endl << "The lowest grade is " << lowestGrade << endl;

    return 0;
}

float findAverage(const GradeType  array, int size)
{
    float sum = 0;   // holds the sum of all the numbers

    for (int pos = 0; pos < size; pos++)
        sum = sum + array[pos];

    return (sum / size);  //returns the average
}

int   findHighest(const GradeType array, int size)
{
    // Fill in the code for this function
    float highestGrade = array[0];

    for (int i = 0; i < size; i++)
    {
        if (array[i] > highestGrade)
            highestGrade = array[i];
    }

    return highestGrade;
}

int   findLowest(const GradeType array, int size)
{
    // Fill in the code for this function
    float lowestGrade = array[0];

    for (int i = 1; i < size; i++)
    {
        if (array[i] < lowestGrade)
            lowestGrade = array[i];
    }

    return lowestGrade;
}

由于错误,程序无法输出最高和最低等级。

标签: c++visual-studio-2012

解决方案


findLowest(grades, lowestGrade);

lowestGrade您在初始化它之前正在使用它。

int lowestGrade; 

应该

int lowestGrade = 0;  // or to anything that has meaning for your app.

当然,作为更好的 C++,在你需要它之​​前声明它,而不是在函数的顶部。

其他变量也一样。

如果逻辑是正确的,所有这一切当然是正确的。为什么将最低/最高等级作为函数中的大小参数传递?


推荐阅读