我无法计算出这个平均值,它一直显示 0

I can't get this mean calculated, it just displays 0 all the time

我搞不懂这个意思,哪里弄错了?由于某种原因,它似乎完全跳过了均值函数。

#include <stdio.h>
double mean(double n[10], int i);

int main()
{
    double n[10];
    int i;
    double x = 0, ave;

    for (i = 0 ; i < 10 && x >= 0 ; i++)
    {
        printf("Enter your value\n");
        scanf("%f", &n[i]);
        printf("%d", n[i]);
    }
    if (i == 10)
    {
        printf("maximum quantity of values reached\n");
    }
    ave = mean(n, i);
    printf("%f", ave);
    return 0;
}
double mean(double n[],int i)
{
    int j;
    double sum = 0.0;
    for (j = 0 ; j < i ; j++)
    {
        sum += n[j];
    }
    return (sum / i);
}

有几件事需要解决,最重要的是

scanf("%f", &n[i])

这是未定义的行为,因为"%f"需要指向float而不是double的指针,您应该将其更改为[=24] =]

scanf("%lf", &n[i])

或将 n 的类型更改为 float

另一个问题是 x 永远不会改变,所以无论输入是什么,条件 x >= 0 始终为真。也许你的意思是

x = n[i];

循环内部。

最后的建议引入了一个新问题,你不检查scanf()的return值所以你不能保证x >= 0是定义的行为。

这是我可以建议的修复方法

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

double mean(double n[10], int i);
int getdouble(double *value);

int main()
{
    double n[10];
    int i;
    double x = 0, ave;

    for (i = 0 ; ((i < 10) && (x >= 0)) ; i++)
    {
        int retry;
        do
        {
            printf("Enter the %ith value > ", i + 1);
            retry += 1;
        } while ((getdouble(&n[i]) != 0) && (retry < 10));
        x = n[i];
    }

    if (i == 10)
        printf("maximum quantity of values reached\n");
    ave = mean(n, i);

    printf("%f", ave);
    return 0;
}
double mean(double n[], int count)
{
    int j;
    double sum = 0.0;
    for (j = 0 ; j < count ; j++)
        sum += n[j];
    return sum / ((double) count);
}

int getdouble(double *value)
{
    char buffer[100];
    char *endptr;
    if (fgets(buffer, sizeof(buffer), stdin) == NULL)
        return -1;
    *value = strtod(buffer, &endptr);
    if ((*endptr != '[=13=]') && (isspace((unsigned char) *endptr) == 0))
        return -1;
    return 0;
}

请注意,我不使用 scanf(),因为很难做到正确。

    scanf("%f", &n[i]);
    printf("%d", n[i]);

指令 %f 表示参数是 float * 类型 scanfdoublefloat 值被提升为)printf...这让我想知道你为什么选择使用 %d 作为 printf?

%d 指令表示参数的类型为 int * for scanfint for printf.

&n[i]double * 类型,所以你在骗 scanfn[i]double 类型,所以你也在骗 printf。这两个谎言都会产生未定义的行为。查看 section 7.21.6.2, paragraph 10 哪个州:

... If this object does not have an appropriate type, or if the result of the conversion cannot be represented in the object, the behavior is undefined.

... 和 section 7.21.6.1, paragraph 9 其中指出:

... If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

您应该为 scanf 使用 %lf 指令。正如我之前提到的,%f 指令可以很好地打印 doubles(或 floats,由于上述提升),但您也可以使用 %lf如果您选择使用 printf 打印 floats 或 doubles。

在使用这些值之前,您可能还应该检查 scanf 的 return 值,因为无法保证它们的完整性(例如,用户可能输入了肮脏的非数字数据)除非你这样做。