gpt4 book ai didi

c - 如何仅取二维数组的某些行和列的平均值?

转载 作者:行者123 更新时间:2023-11-30 16:25:51 27 4
gpt4 key购买 nike

我必须只取测试成绩的平均值并将其放入最后一列,但我不知道该怎么做。我有一个二维数组的函数,它接受包含成绩的文件名,但第一列是学生 ID,所以我不需要取平均值。

这是我的二维数组函数的代码。

#define x 10
#define y 6

void getData(float arr1[x][y])
{
FILE* graFile;
float arr2[x][y];
char userIn[50];
printf("Enter the text filename: ");
scanf("%s", userIn);
graFile = fopen(userIn, "r");
int studentId, test1, test2, test3, test4;
for(int i = 0; i < x; i++)
{
if(graFile != NULL)
{
fscanf(graFile, "%d%d%d%d%d", &studentId, &test1, &test2, &test3, &test4);
arr2[i][0] = studentId;
arr2[i][1] = test1;
arr2[i][2] = test2;
arr2[i][3] = test3;
arr2[i][4] = test4;
}
else
{
printf("\nThis file does not exist.");
return;
}
}
printf("\n %11s%11s%11s%11s%11s%11s", "Student Id","Test 1","Test 2","Test 3","Test 4","Final\n");
printf("*********************************************************************\n");
for(int i = 0; i < x; i++)
{
for(int j = 0; j < y; j++)
{
printf("%11.0f", arr2[i][j]);
}
printf("\n");
}
printf("*********************************************************************\n");
fclose(graFile);
return;
}

这给了我这个输出

Enter the text filename:  grades.txt

Student Id Test 1 Test 2 Test 3 Test 4 Final
*********************************************************************
6814 85 86 92 88 0
7234 76 81 84 78 0
6465 87 54 68 72 0
7899 92 90 88 86 0
9901 45 78 79 80 0
8234 77 87 84 98 0
7934 76 91 84 65 0
7284 56 81 87 98 0
7654 76 87 84 88 0
3534 86 81 84 73 0
*********************************************************************

现在我只需要创建一个新函数来平均该数组的测试成绩并将其放入最后一列,但我在执行此操作时遇到了困难。我很感激我能得到的任何帮助。

最佳答案

void setAverage(float arr[][y], int x) {
for(int i = 0; i < x; i++) {
arr[i][5] = (arr[i][1] + arr[i][2] + arr[i][3] + arr[i][4]) / 4;
}
}

关于c - 如何仅取二维数组的某些行和列的平均值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53245419/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com