为什么我的程序有时只能正确识别数组中的最高和最低值



我正在编写一个家庭作业程序,其中除其他外,还必须能够输出数组中的最高和最低值。该数组中的十个数值(称为int in int of程序的上下文(的十个值是由用户尽早输入的。我有两个函数,分别计算出最高和最低的int阵列。由于我无法弄清楚的原因,GethighScore函数仅有时仅正确地确定最大值,具体取决于已存储的int int arnare和getlowscore函数返回的值始终确定最低数字是由GethighScore返回的最低数字是相同的数字。

我已经尝试将我的代码与我过去的程序和在线旨在达到相同目的的在线代码进行比较,尽管它几乎与一个示例相同,但我的getlowscore函数仍然永远无法按预期工作。我相信它也值得在我的程序中包括计算以下数组内容的平均值的功能,就像它使用不同的命令一样,它始终按预期工作,我不确定是什么与其他两个功能区分开来。

//Stores the highest score in the array in the "highest" variable
int getHighScore (/*in*/const int somearray[], /*in*/int size)
//PRE: The contents of the array have been defined, as well as the 
//variable "size"
//POST: The largest value in the array is stored in the "highest" variable
{
    int highest = 0;
    highest = somearray [0]; //Set highest to the first element in the array
    for (int index = 1; index < size; index++)
    {
        if (somearray [index] > highest);
            highest = somearray [index];
    }
    return highest;
}
//Stores the lowest score in the array in the "lowest" variable
int getLowScore (/*in*/const int somearray[], /*in*/int size)
//PRE: The contents of the array have been defined, as well as the 
//variable "size"
//POST: The lowest value in the array is stored in the "lowest" variable
{
    int lowest = 0;
    lowest = somearray [0]; //Set lowest to the first element in the array
    for (int index = 1; index < size; index++)
    {
        if (somearray [index] < lowest);
            lowest = somearray [index];//
    }
    return lowest;
}
//Stores the mean of all the values in the array in the "average" variable
int getAvgScore (/*in*/const int somearray[], /*in*/int size)
//PRE: The contents of the array have been defined, as well as the 
//variable "size"
//POST: The average value in the array is stored in the "average" variable
{
    int totalScore = 0;
    double average = 0;
    //average = somearray [0]; //Set highest to the first element in the 
array
    for (int index = 0; index < size; index++)
    {
        totalScore += somearray [index];
    }
    average = totalScore / 10;
    return average;
}

此代码编译,但是逻辑错误使我无法实现所需的结果。

这是这些行:

if (somearray [index] > highest);
            highest = somearray [index];

应该是这样的东西:

if (somearray [index] > highest) {
            highest = somearray [index];
}

注意:您可能会或可能不会犯同样的错误,所以我会仔细检查我是否是您。

我认为 @chipster的答案正确,避免错误的另一个建议是将您的编译警告视为错误。

因为如果您仔细检查您的编译警告,您会发现至少一个警告(我使用clang(

warning: if statement has empty body [-Wempty-body]
    if (somearray [index] > highest);

我在getlowscore/gethighscore方法中看到的唯一问题是,如果大小为零,它们可能会非常错误。否则,那里没有问题。没有提供任何其他上下文如何使用这些方法,不可能更加可悲地帮助。

我在getavgscore方法中只能看到其他问题是您想将.0附加到这里:

average = totalScore / 10.0;

(否则,平均水平只能最终成为整数(。另外,从getavgscore中返回双倍的人是明智的吗?如果那是施放在使用的地方的地方,那就这样吧。但是至少您正在返回小数点右侧的额外数字,以防万一。

相关内容

最新更新