为什么我的作业出现逻辑错误?

时间:2009-01-11 20:29:58

标签: c fencepost

我是IT的初级学生。我正面临着程序输出的问题。 程序的想法是我应该使用函数来读取10个元素的数组,然后得到元素的平均值,然后得到最大值和最小值。我有最大和最小的权利,但平均值显示奇怪的东西。请检查代码并告诉我应该做什么或以某种方式帮助我。

输出是(通知是请求11个数字而不是10个,如果我改变循环参数让它只需要10个,那么它会显示奇怪的东西

enter the group of integers numbers
1
2
3
4
5
6
7
8
9
0
9
 1 2 3 4 5 6 7 8 9 0the avg is 3.500000
9
1Press any key to continue . . .

// func-sortarray.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#define size  10

void readarray(int []);
void average(int []);
void printArray(int []);
void max(int []);
void min(int []);

int _tmain(int argc, _TCHAR* argv[])
{
    int sarray[size];
    readarray(sarray);
    printArray(sarray);
    average(sarray);
    max(sarray);
    min(sarray);
    return 0;
}

void readarray(int a[])
{
    printf("enter the group of integers numbers\n");
    for (int i=0; i<=size-1 ;i++)
        scanf("%d\n",&a[i]);
}

void average(int a[])
{
    int i;
    double avg;
    double total = 0;
    for (i=0; i <= size-1; i++)
    {
        total = total + a[i];
    }

    avg = total /size-1;
    printf("the avg is %f\n",avg);
}

void printArray(int a[])
{
    int j;
    for (j = 0; j <= size - 1; j++) 
        printf( "%2d", a[ j ]);
}

void max(int a[])
{
    int ma =a[0];

    for (int j=0;j<size-1;j++)
    {
        if (ma<a[j])
            ma=a[j];
    }
    printf("%d",ma);
}

void min(int a[])
{
    int mi =a[0];

    for (int j=0;j<size-1;j++)
    {
        if (mi>a[j])
            mi=a[j];
    }
    printf("\n%d",mi);
}
提前

thanx

3 个答案:

答案 0 :(得分:3)

在添加规则之前,从零开始计数并且相乘时,您遇到了一些问题。好吧,让我们开始吧。最常见的是,当你从零开始计数时,你会这样做:

for(i=0; i < count; i++)
    /* ... */;

如果你从1开始计算,你可以这样做:

for(i=1; i <= count; i++)
    /* ... */

如果你混合使用它们,你会得到相同的结果,但它会使你自己和其他人阅读代码感到困惑:

for(i=0; i <= count-1; i++) /* same, but better don't do this */
    /* ... */;

在计算平均值的代码中,你有两个错误。首先,你应该使用括号,因为数学:

avg = total / (size-1); /* there is still one bug */

其次,你拥有 size元素。因此,您必须除以size,而不是size-1

avg = total / size; /* right ! */

答案 1 :(得分:2)

这一行可能是问题所在:

avg = total /size-1;

你可能想要改为:

avg = total / size;

此外,您的max()min()函数的循环如下:

for (int j=0;j<size-1;j++)

这可能比你想要的少一个。

上述类型的错误通常被称为“fencepost错误”。这个名字涉及到以下问题:如果你想要建造一个100米长的栅栏,并且你想要每隔1米有一个栅栏柱,你需要多少栅栏柱?答案不是100而是101.这种错误的另一个名称是“一个错误”。

答案 2 :(得分:1)

由于scanf()字符串中的'\ n',它正在跳过第一个输入数字。要修复它,请从scanf字符串中删除'\ n',如下所示:

scanf("%d", &a[i]);