基于test.h文件,该函数应输出1.000作为平均值,但我得到错误的值输出 数组的每个位置保存的值是1.0, 并且4 * 5 * 10 = 200是总位置
#include <stdio.h>
#include "test.h"
float avgLeaguePlayer(float leagueTeams[4][5][10]);
int main()
{
while (1)
{
printf("MENU\n");
printf("=====\n");
printf(" 1. Entire League Average Player Rating\n");
printf(" 2. Second Function\n");
printf(" 3. Third Function\n");
printf(" 4. Exit\n");
printf("Enter selection : ");
int sel;
float averagePlayer;
scanf("%d", &sel);
switch (sel)
{
case 1:
averagePlayer = avgLeaguePlayer(leagueTeams);
printf("Average Player Rating: %f\n", averagePlayer);
break;
case 2:
printf("2\n");
// call function 2;
break;
case 3:
printf("3\n");
// call function 3;
break;
case 4:
break;
default:
printf("Invalid Input\n");
}
break;
}
}
float avgLeaguePlayer(float leagueTeams[4][5][10])
{
int layerOne = 0;
int layerTwo = 0;
int layerThree = 0;
float sum = 0.0;
float avg = 0.0;
for (layerOne = 0; layerOne < 4; layerOne++)
{
for (layerTwo = 0; layerTwo < 5; layerTwo++)
{
for (layerThree; layerThree < 10; layerThree++)
{
sum += leagueTeams[layerOne][layerTwo][layerThree];
}
}
}
avg = (sum / 200);
return avg;
}
我需要帮助格式化代码以获得正确的输出。我是c的新手,谢谢
答案 0 :(得分:5)
这里有一个问题
for(layerThree; layerThree<10; layerThree++)
这是第一次迭代这个嵌套循环时很好,因为layerThree
在定义时被初始化为0
。但对于后续迭代,layerThree
不会重置为0
。实际上它是10
所以循环永远不会再次迭代。所以内循环应该是
for(layerThree = 0; layerThree < 10; layerThree++)