用c编程语言编写的智力竞赛游戏中的错误分数



我在看一个C教程,我想出了一个智力竞赛游戏,代码如下:

char questions[][100] = {"1. What year did the C language debut?: ", 
"2. Who is credited with creating C?: ",
"3. What is the predecessor of C?: "};
char options[][100] = {"A. 1969", "B. 1972", "C. 1975", "D. 1999",
"A. Dennis Ritchie", "B. Nicola Tesla", "C. C. John Carmack", "D. Doc Brown",
"A. Objective C", "B. B", "C. C++", "D. C#"};
char answers[3] = {'B', 'A', 'B'};
int numberOfQuestions = sizeof(questions)/sizeof(questions[0]);
char guess;
int score;
printf("QUIZ GAMEn");
for(int i = 0; i < numberOfQuestions; i++)
{
printf("***********************n");
printf("%sn", questions[i]);
printf("***********************n");
for(int j = (i * 4); j < (i * 4) + 4; j++)
{
printf("%sn", options[j]);
}
printf("guess: ");
scanf("%c", &guess);  
scanf("%*c"); 
guess = toupper(guess);
if(guess == answers[i])
{
printf("CORRECT!n");
score++;
}
else
{
printf("WRONG!n");
}
}
printf("***********************n");
printf("FINAL SCORE: %d/%dn", score, numberOfQuestions);
printf("***********************n");
return 0;

}

在bash脚本中运行代码时,我的分数不是2/3或3/3,而是以下值:1819435367/3或3483/3

你知道我在程序中做错了什么吗?

int score;声明了一个变量,但不会将其初始化为任何特定值,因此其值将是不确定的。假设这个值是在函数中声明的,它将使用堆栈内存,它的值将是这个内存位置中以前的任何位,现在被解释为int。解决方案是初始化变量:int score = 0;

或者,您也可以在文件范围(通常称为全局范围(中声明变量,并使其成为静态变量。这保证了(除其他外(整数将被初始化为0。示例:

static int score;
int main(void)
{
print("%dn", score);  // this will print '0'
}

要避免此类错误,请在启用所有警告的情况下编译程序(使用-Wall标志(。要追踪这些错误,请使用Valgrind运行您的程序。

最新更新