gpt4 book ai didi

C 程序,收到有关未初始化变量的错误,程序永远不会结束

转载 作者:行者123 更新时间:2023-11-30 14:54:27 28 4
gpt4 key购买 nike

#define _CRT_SECURE_NO_WARNINGS     
#include <stdio.h>
#include <ctype.h>
#define MAXGUESSES 5


void Instructions();


int PlayGuess(char solution);


char GetLetter();


int CompareLetters(char guess, char solution);




int main()
{
int i = 0;
int numgames = 0;
char solution;
char guess;
int compareletter(char guess, char solution);
FILE *inp;
inp = fopen("letterList.txt", "r");
fscanf(inp, "%c", &solution);
Instructions();
//get number of games the user wants to play
printf("Please enter the number of games you want to play\n");
scanf("%d", &numgames);
for (i = 1; i <= numgames; i++)
//print current game (value of i)
{
//get letter to guess from file
fscanf(inp, "%c", &solution);
PlayGuess(solution);
printf("\nThe letter is %c\n", solution);
}


fclose(inp);

}
void Instructions()
{
printf("Welcome to Letter Guess\n");
printf("To begin you will enter the number of games you want to
play(1 – 4 games)\n");
printf("You have 5 chances to guess each letter\n");
printf("Let's begin\n");

}

int PlayGuess(char solution) //player defined guesses.
{
int numGuesses = 0;
int winOrLose = 0;
while (numGuesses < MAXGUESSES)
{
GetLetter();

numGuesses = numGuesses + 1;
if (numGuesses>MAXGUESSES)
{
printf("You have run out of guesses\n");
}
}


return 0;
}


//get the guess from the user (call GetLetter function)
//call compareLetters function

char GetLetter()
{
char guess = 0;
char solution;
printf("Enter a guess:", guess);
scanf(" %c", &guess);
CompareLetters(guess, solution);
return guess;
}


//compare the guess and the solution
//return a 1 if they are the same
// message based on before or after alphabetically
//return a 0 if the guess and answer are not the same

int CompareLetters(char guess, char solution)
{
if (guess == solution) //if answer is correct
{ printf("Thats it!\n");
return 1;
}
else
if (guess<solution)
{
printf("The letter you are trying to guess comes after %c\n", guess);
printf("\nTry again\n");
GetLetter();

return 0;
}
else
if (guess>solution)
{ printf("The letter you are trying to guess comes before %c", guess);
printf("\nTry again\n");
GetLetter();
return 0;
}
}

抱歉,如果代码有点困惑。

问题#1:变量“solution”未初始化,但我不知道如何修复它。我经常遇到这个问题,如果可能的话我可以使用解释。

问题#2:当我启动程序并输入我想玩的游戏数量时,它会忽略它并给我无尽的猜测,程序永远不会停止。

谢谢。

最佳答案

  1. 只需输入char Solution = '\0';。摆脱警告就足够了。
  2. 尝试打印您刚刚在 scanf() 函数中读取的 numgames 值。由于某种原因,您似乎获得了一些无效值...

更新:我看到您的问题:您正在从 PlayGuess() 调用 GetLetter();并且您正在从 GetLetter() 调用 CompareLetters();然后从 CompareLetters() 调用 GetLetter(),这样就创建了无限递归。从 CompareLetters() 中删除调用 GetLetter()

关于C 程序,收到有关未初始化变量的错误,程序永远不会结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46679238/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com