#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(void)
{
char start;
int num, gold, times, balance;
start = 'y';
printf("Do u want wealth overnight?\n");
printf("Let´s play a game\n");
printf("How much money do you want to pay for the game?\n");
scanf("%d",&gold);
times = gold/2;
while (start == 'y' || start == 'Y')
{
while (gold >= 2)
{
printf("You have %d chances.\n",times);
srand( (unsigned)time( NULL ) );
num = rand()% 15+3;
printf("Your number is : %d\n",num);
fflush(stdin);
if (num == 18 || num == 3)
{
gold = gold + 8;
times = gold/2;
printf("Congratulations! You win 10 euro!\n");
printf("Your balance is %d. \n",gold);
}
else if (num >= 16 || num == 5)
{
gold = gold + 1;
times = gold/2;
printf("Congratulations! You win 3 euro!\n");
printf("Your balance is %d. \n",gold);
}
else
{
gold = gold - 2;
times = gold/2;
printf("You lose, try again!\n");
printf("Your balance is %d. \n",gold);
}
printf("Do you want to try again?(y/n)\n");
scanf("%c", &start);
fflush(stdin);
}
printf("Your balance is not enough, Welcome to come again.");
}
return 0;
}
这个问题的出现是你想当然了。
按你的想法,大概是:循环结束的标记start是y,如果start不是y,那就应该立刻跳出循环
但你没有注意到你套了两层循环啊。
程序执行是按行依次执行,在执行到
printf("Do you want to try again?(y/n)\n");
scanf("%c", &start);
代码后,程序首先是处理
fflush(stdin);
}
printf("Your balance is not enough, Welcome to come again.");
代码段中的‘}’,它回到了
while (gold >= 2)
{
printf("You have %d chances.\n",times);
srand( (unsigned)time( NULL ) );
这个‘{’对应的小循环,此时就继续执行程序了,因为小循环的条件:gold>=2还是成立的。
只有在gold<2,执行了 printf("Your balance is not enough, Welcome to come again."); 语句后,才会执行大循环的条件判定,跳出大循环
当然,核心问题不是两层循环,你需要注意的是循环终止的判定是在当前轮的循环结束时发生的,在那之前的语句属于当前轮,依旧是有效的!
码字不易,望采纳,谢谢!
C和C++完整教程:https://blog.csdn.net/it_xiangqiang/category_10581430.html