C 基本的;";尝试写入播放器时出现编程错误';谁的名字在平均数之前
这是我写的代码C 基本的;";尝试写入播放器时出现编程错误';谁的名字在平均数之前,c,C,这是我写的代码 #include<stdio.h> int main() { char playerName; int gameScores [10]= {12,5,21,15,32,10}; int totalPoints=0; int x; float avg; for (playerName='A'; playerName<='Z'; playerName=playerName+1) { prin
#include<stdio.h>
int main()
{
char playerName;
int gameScores [10]= {12,5,21,15,32,10};
int totalPoints=0;
int x;
float avg;
for (playerName='A'; playerName<='Z'; playerName=playerName+1)
{
print("%c",playerName);
scanf ("/%s",playerName[x]);
}
putchar('\n');
for(x=6; x<10; x++)
{
printf ("What did the player score in game %d?". x+1);
scanf ("%d", &gameScores [x]);
}
for(x=0; x<10; x++)
{
totalPoints +=gamesScores[x];
}
avg=((float) totalPoints/10);
printf("\n\nThe Play's scoring average is %.1f.\n", avg);
return (0)
}
它不断地出现错误。它表示下标值不是数组、指针或向量。我想在平均得分之前列出球员的名字。没有scanf if,只给我输入上面的字母表而不是球员的名字。
char playerName
只是一个字符,一个字节。C字符串是字符数组,以零(NUL)字符结尾。因此,被视为字符串的单个字符只能保存终止NUL,而不能保存其他内容,即它只能是空字符串
您需要将playerName
定义为一个足以容纳名称+终止NUL的数组,例如:
#定义最大名称长度100
char playerName[最大名称长度+1];
这对于单个名称就足够了,但由于您有多个播放器,因此您需要这些数组的数组,例如:
#定义最多10名玩家
#定义最大名称长度100
char playerName[MAX_PLAYERS][MAX_NAME_LENGTH+1];
(您也可以动态分配内存,例如使用malloc
,但这超出了问题的范围。)
另外,您的scanf
在格式字符串中有一个额外的斜杠/
,这会导致它失败,除非每个玩家的名字在输入前都有一个斜杠,我猜情况并非如此。也许你想用反斜杠\
来转义%
,但这里也不需要,因为百分号只在printf
/scanf
格式字符串中是“特殊”的,而不是在C本身中
在正确的程序中,当使用scanf
读取时,还需要防止缓冲区溢出。并且应该检查scanf
的返回值,以验证输入是否被成功读取(如果没有,可能重试或中止程序)。有关返回值和参数,请参阅scanf
(以及您使用的所有其他函数)的文档
(总的来说,我建议学习使用
fgets
将行读入缓冲区,因为通常很难以合理的方式从scanf
错误中恢复,尤其是当格式字符串变得更加复杂时。)从scanf(“/%s”,playerName[x])playerName+x
或者,如果您愿意,&(playerName[x])
。另外,您不初始化x
,这是另一个问题。playerName
是单个字符。还可以将其用作循环变量。这应该如何命名?您需要另一个变量,它是一个字符数组。您没有初始化数组中的所有元素,因此其中可能有一些愚蠢的值:intgamescores[10]={12,5,21,15,32,10}代码>--您要求10个元素,但仅初始化其中6个。您的意思是:for(x=6;xy)除非您检查返回,否则无法正确使用任何用户输入。没有playerName[x]
,playerName
是类型char
,而不是数组,例如char[26]
。
scanf("/%s",playerName [x]);