到目前为止,我可以使该代码工作的唯一方法是使用 switch 语句。有没有办法可以去掉这个 switch 语句并创建一个数组。我听说我可以这样做: char name[11]= {"name 1", "name 2"};
等等,但我不确定稍后如何在程序中打印它。因为对于我的数字,我只是将其分配给一个非数组变量并使用 printf 来打印它。
我的代码:
#include <stdio.h>
int main(){
int i;
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 bestplayer = 0;
float bestppg = 0.0;
float ppg [11] ;
for (i=0; i<11; i++){
ppg[i] = (float)points [i] / (float)games [i] ;
printf("%d \t %d \t %d \t %.1f ppg\n", player[i], games[i], points[i],ppg[i]);
if (ppg[i]>bestplayer){
bestplayer = player[i];
bestppg = ppg[i];
}
}
printf("\nThe player with the most points per game is #%d ", bestplayer);
switch(bestplayer){
case 1:
printf("Player 1");
break;
case 2:
printf("Player 2");
break;
case 10:
printf("Player 3");
break;
case 13:
printf("Player 4");
break;
case 21:
printf("Player 5");
break;
case 22:
printf("Player 6");
break;
case 24:
printf("Player 7");
break;
case 25:
printf("Player 8");
break;
case 31:
printf("Player 9");
break;
case 32:
printf("Player 10");
break;
case 33:
printf("Player 11");
break;
default:
printf("Invalid Player");
break;
}
printf(" with %.1f ppg.\n",bestppg);
return 0;
}
最佳答案
在当前结构中使用 char*
数组的主要问题是您没有跟踪最佳玩家的索引。如果这样做,那么您只需创建一个数组并为其建立索引即可。
#include <stdio.h>
int main(){
int i;
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};
const char* names[11] = {
"Jaylon Tate","Joseph Bertrand","Jaylon Tate","Tracy Abrams","Malcolm Hill","Maverick Morgan","Rayvonte Rice","Kendrick Nunn","Austin Colbert","Nnanna Egwu","Jon Ekey"
};
int bestplayer = 0;
float bestppg = 0.0;
float ppg [11] ;
int bestIndex = 0;
for (i=0; i<11; i++){
ppg[i] = (float)points [i] / (float)games [i] ;
printf("%d \t %d \t %d \t %.1f ppg\n", player[i], games[i], points[i],ppg[i]);
if (ppg[i]>bestplayer){
bestplayer = player[i];
bestppg = ppg[i];
bestIndex = i;
}
}
printf("\nThe player with the most points per game is #%d %s with %.1f ppg.\n", bestplayer, names[bestIndex], bestppg);
return 0;
}
关于c - 如何在 C 中创建字符串数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26309998/