【发布时间】:2014-02-13 21:29:02
【问题描述】:
不过,我第一次玩这款游戏时运行良好;第二次它只给你两条生命......我试图改变生命的数量,但仍然无法弄清楚我做错了什么。
// 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
-
另外你打印出“你有 5 次尝试”但声明你只想要“3”...
-
请格式化并正确缩进您的代码!试图从源代码中查找错误是没有意义的,这会试图误导和混淆程序员(通过不显示循环等的正确缩进位置)。
-
“scanf("%d",&num1);" 下方还有一个额外的花括号。你应该使用“&&”而不是“||”以及删除“}while(num1!=r || x
-
非常感谢你!小错误只是因为改变周围的事物并让我想到你知道的事情,也感谢你的建议和什么不是人。当你看东西有点久,它会变得模糊时总是很难的,哈哈,一双新的眼睛总是有帮助的,谢谢你:)
标签: c for-loop while-loop do-while srand