使用变量、数组和函数进行准确的求和平均值计算

Using variables, arrays, and functions for accurate sum and average calculation

提问人:Abed Nehme 提问时间:5/23/2023 最后编辑:BarmarAbed Nehme 更新时间:5/23/2023 访问量:54

问:

我是编程新手,但我的代码包括一个数组,一直给出 0 作为数组的总和。我的代码是:

/*y = (1 / (p * sqrt(2π))) * e^((-1/2) * ((a - x) / p)^2)

在这个等式中:

我试图从一侧(总和和平均值)解决它,但事情对我来说并不顺利。

/* 
a represents the grade or score achieved by a student.
y represents the probability density of obtaining that grade.
x represents the mean (average) grade.
p represents the standard deviation, which measures the spread or variability of the grades.*/
#include <stdio.h>
#include <math.h>
float curve(int a, float p, float x);
int main()
{
    int i = 0, grade[100], sum = 0, n = 0, success = 0, fail = 0, low = 100, high = 0;
    float avg, sd;
    printf("ente the grade:\n");
    scanf("%d", &grade[i]);
    while (grade[i] != -1)
    { // grade[i] >=60? success++:fail++;
        // if (grade[i]>high)
        // high=grade[i];
        // if (grade[i]<low)
        // low=grade[i];
        n++;
        i++;
        sum = sum + (grade[i]);
        printf("ente the grade:\n");
        scanf("%d", &grade[i]);
    }
    for (i = 0; i < n; i++)
    {
        printf("%d\n", grade[i] + 10);
    }
    avg = sum / n;
    // sd=pow(garde)
    printf("the sum of the class is %d\n", sum);
    printf("the average of the class is %f\n", avg);
    printf("the number of the student who passed the exam is %d\n", success);
    printf("the number of the student who failed the exam is %d\n", fail);
    printf("the highest mark in the class is %d\n", high);
    printf("the lowest mark in the class is %d\n", low);
    if (avg < 50)
    {
        printf("raise suggested\n");
        printf("the new average of the class is %f\n", (avg + 10));
    }
    else if (avg > 50 && avg < 60)
    {
        printf("curve suggested\n");
    }
    return 0;
}
float curve(int a, float p, float x)
{
    float y;
    y = (1 / (p * sqrt(2 * (3.14159)))) * pow((2.718), ((-1 / 2) * ((a - x) / p) * ((a - x) / p)));
    return y;
}
数组 C 变量

评论

1赞 Ted Lyngmo 5/23/2023
(奇怪的是,如果不添加一些样板,我无法对这个问题发表评论 - 它说这是因为我投了反对票,但我没有)无论如何:结果是因为它是一个整数除法。你可能想要(-1 / 2)0(-1. / 2)
0赞 Barmar 5/23/2023
你从不打电话,为什么相关?curve()
0赞 Barmar 5/23/2023
sum = sum + (grade[i]);需要之前。您要向 添加下一个元素,而不是用户刚刚输入的元素。i++sum
0赞 Weather Vane 5/23/2023
顺便说一句:你对 e 有一个可怕的近似值。这和π可能在库中定义。另外,除非有很好的理由必须使用,否则请使用。math.hdoublefloat
2赞 William Pursell 5/23/2023
@WeatherVane不是图书馆math.h

答:

0赞 Chris 5/23/2023 #1

如注释中所述,读取输入存在问题。建议您使用...while 循环,因为您需要至少循环一次

int main(void) {
    int grades[100];
    int n = 0;

    do {
        scanf("%d", &grades[n++]);
    } while (n < 100 && grades[n-1] != -1);

    n--; // exclude the -1 value
}

现在,您可以轻松地遍历这些值以找到总和,并从中找到平均值。

这应该是错误检查返回值,但这是另一个问题。这里将记录输入的成绩数。scanfn

还要记住,对两个整数进行数学运算将始终产生整数结果,即使该值随后被分配给 or 变量也是如此。floatdouble

评论

1赞 William Pursell 5/23/2023
必须检查 返回的值。也许scanfwhile( n < 100 && 1 == scanf("%3d", grades + n) && grades[n++] != -1 ) { ... }