提问人:Abed Nehme 提问时间:5/23/2023 最后编辑:BarmarAbed Nehme 更新时间:5/23/2023 访问量:54
使用变量、数组和函数进行准确的求和平均值计算
Using variables, arrays, and functions for accurate sum and average calculation
问:
我是编程新手,但我的代码包括一个数组,一直给出 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;
}
答:
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
}
现在,您可以轻松地遍历这些值以找到总和,并从中找到平均值。
这应该是错误检查返回值,但这是另一个问题。这里将记录输入的成绩数。scanf
n
还要记住,对两个整数进行数学运算将始终产生整数结果,即使该值随后被分配给 or 变量也是如此。float
double
评论
1赞
William Pursell
5/23/2023
必须检查 返回的值。也许scanf
while( n < 100 && 1 == scanf("%3d", grades + n) && grades[n++] != -1 ) { ... }
评论
(-1 / 2)
0
(-1. / 2)
curve()
sum = sum + (grade[i]);
需要之前。您要向 添加下一个元素,而不是用户刚刚输入的元素。i++
sum
math.h
double
float
math.h