【问题标题】:C simple array code isn't workingC 简单数组代码不起作用
【发布时间】:2014-10-12 02:24:08
【问题描述】:

我的代码是:

#include <stdio.h>
int main(){
int i, choice;
int player [11] = {1,    2,   10,   13,   21,  22,  24,   25, 31,32,   33};
int points [11] = {60, 297, 11, 373, 154, 52, 555, 218, 29, 242, 257};
int games [11] = {33, 35,  12,  35,   35,  35,  35,   35, 22,35,   35};
int assists [11] = {64 , 27 ,   2   ,  112  , 23 ,  3  ,   53 ,  39 ,  4 , 15 ,   9 };
int rebounds[11] = {30,134,3,122,85,43,210,58,17,211,169};
const char* names[11] = {
    "Jaylon Tate","Joe Bertrand","Jaylon Tate","Tracy Abrams","Malcolm Hill","Mav Morgan","Rayvonte Rice","Kendrick Nunn","Austin Colbert","Nnanna Egwu","Jon Ekey"
};
printf("Number\tGames\tPoints\tAssists\tRebounds\n");
int bestplayerppg = 0;
int bestplayerapg = 0;
int bestplayerrpg = 0;
float bestppg = 0.0;
float bestapg = 0.0;
float bestrpg = 0.0;
float ppg [11] ;
float apg [11];
float rpg [11];
int bestIndexppg = 0;
int bestIndexapg = 0;
int bestIndexrpg = 0;
for (i=0; i<11; i++){
    ppg[i] = (float)points [i] / (float)games [i] ;
    apg[i] = (float)assists [i] / (float)games [i] ;
    rpg[i] = (float)rebounds [i] / (float)games [i] ;
    printf("%s \t %d \t %d \t %d \t %d \t %.1f ppg \t %.1f apg \t %.1f rpg\n", names[i], games[i], points[i], assists[i], rebounds[i], ppg[i], apg[i], rpg[i]);
    if (ppg[i]>bestplayerppg){
        bestplayerppg = player[i];
        bestppg = ppg[i];
        bestIndexppg = i;
    }
     if (apg[i]>bestplayerapg){
        bestplayerapg = player[i];
        bestapg = apg[i];
        bestIndexapg = i;
    }
    if (rpg[i]>bestnorpg){
        bestplayerrpg = player[i];
        bestrpg = rpg[i];
        bestIndexrpg = i;
    }
}
printf("Pick the stat you want to view:\n1. Points per game\n2. Assists per game\n3. Rebounds per game\nEnter a choice: ");
scanf("%d",&choice);
printf("The player with the most ");
switch (choice){
    case 1:
    printf("points per game is #%d %s with %.1f ppg.\n", bestplayerppg, names[bestIndexppg], bestppg);
    break;
    case 2:
    printf("assists per game is #%d %s with %.1f apg.\n", bestplayerapg, names[bestIndexapg], bestapg);
    break;
    case 3:
    printf("rebounds per game is #%d %s with %.1f rpg.\n", bestplayerrpg, names[bestIndexrpg], bestrpg);
    break;
    default:
    printf("Choice is not valid\n");
} 
}

代码非常适合得分和助攻。但是在找到顶级rpg时它不起作用。它说#13 Tracy aka 数组中的第四个元素在他没有的时候拥有最多的 rpg。我对得分、助攻和篮板的逻辑是一样的,但只有得分和助攻才起作用……

【问题讨论】:

  • 第三个if错了

标签: c arrays string loops if-statement


【解决方案1】:
if (rpg[i]>bestnorpg){
        bestplayerrpg = player[i];
        bestrpg = rpg[i];
        bestIndexrpg = i;
}

bestnorpg 没有在任何地方声明。

尝试以下方法:

if (rpg[i]>bestrpg){
        bestplayerrpg = player[i];
        bestrpg = rpg[i];
        bestIndexrpg = i;
    }

【讨论】:

  • bestrpg不应该是bestplayerrpg吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
  • 2023-03-22
  • 2021-01-07
  • 2023-03-04
相关资源
最近更新 更多