虽然我的第一次游戏运行良好,第二次它只给你两条生命......我试图改变生命的数量,但仍然无法弄清楚我做错了什么。随机数字游戏C
// C_program_random_number_game
#include<stdio.h>
#include<time.h>
#include <stdlib.h>
int main()
{
srand(time(NULL));
int num1,x = 0;
char game, cont, replay;
printf("Would you like to play a game? : ");
scanf("%c",&game);
if (game == 'y' || game == 'Y')
{
printf("\nThe rules are simple. You have have 5 tries to guess the computers number. \n \n If you succeed you win the game, if you dont you lose the game. Good luck!");
do
{
int r = rand()%5 +1;
printf("\n\nEnter a number between 1 and 5 : ");
scanf("\n%d",&num1);
x++;
if(num1 > 0 && num1 < 5)
{
do
{
if(num1 < r)
{
printf("\nClose! try a little higher... : ");
x++;
}
else if (num1 > r)
{
printf("\nClose! try a little lower...: ");
x++;
}
scanf("%d",&num1);
}while(num1!=r && x <3);
if(num1 == r)
{
printf("\nWinner! >> you entered %d and the computer generated %d! \n",num1, r);
}
else if(num1 != r)
{
printf("\nBetter luck next time!");
}
printf("\n\nWould you like to play again? (y or n) : ");
scanf("\n%c",&replay);
}
else
{
printf("Sorry! Try again : ");
scanf("%d",&num1);
}
}while(replay == 'y'|| replay == 'Y');
}
else if (game == 'n' || game == 'N')
{
printf("Okay, maybe next time! ");
}
else
{
printf("Sorry, invalid data! ");
}
return 0;
}
尝试设置一个int为0.如果他们猜错了,则增加它(例如x ++)。这可能在内部的do-while循环中。如果(x == 3)爆发。你的问题是你需要一个“休息”。声明。你的do-while永远重复for循环。如果我明白你想要什么,应该不需要for循环。编辑:另外x总是小于或等于3(按照for循环所说的),所以在while()中检查它没有任何意义。参照“while(num1!= r || x <= 3);” – MrHappyAsthma
此外,您还打印出“你有5次尝试”,但陈述你只想要“3”... – MrHappyAsthma
请格式化并正确缩进你的代码!尝试从源代码中找到错误是毫无意义的,它试图误导和混淆程序员(通过不显示循环等与合适的缩进位置)。 – hyde