c - How would I avoid using a goto statement here?
问题描述
I am pretty new to programming in C and I am making a simple dice based game. I have all the other logic working but I am having trouble seeing how to avoid a goto statement. Basically the player starts with 50 dollars as their balance and the program asks for a bet, then dice are rolled and depending on what the result of the roll is different things happen. The main issue is when the result happens the user is asked if they want to play again, if they say no then I just exit but if they say yes I need to go back to the start and ask for a bet again.
int main()
{
START:
if (FirstRun == 0)
{
printf("Your starting balance is $%.2f", Balance);
}
if (FirstRun > 0)
{
printf("Your new balance is $%.2f", Balance);
}
if (Balance <= 0)
{
printf("Sorry you are out of money!");
exit(0);
}
do
{
ValidBet = 0;
printf("\nPlease enter your bet:");
scanf("%lf", &Bet);
if ((Bet > Balance) || (Bet < 0))
{
printf("Your bet is invalid, try again.");
}
else
{
ValidBet = 1;
}
} while (ValidBet == 0);
ThrowDicePair();
printf("DICE #1 WAS %d", SumOfThrows);
if (SumOfThrows == 7 || SumOfThrows == 11)
{
Balance += Bet;
printf("You win! Would you like to play again? [y/n]");
C = getch();
if (C == 'y')
{
FirstRun++;
goto START;
}
else if (C == 'n')
{
printf("Thanks for playing");
exit(0);
}
}
解决方案
只需将所有内容放在一个for(;;)
循环中;goto将是您重新循环的情况,在其他情况下添加一个(return 0;
或者exit(0);
您喜欢并且在某些情况下已经使用)
int main()
{
for (;;) { /* ADDED */
if (FirstRun == 0)
{
printf("Your starting balance is $%.2f", Balance);
}
if (FirstRun > 0)
{
printf("Your new balance is $%.2f", Balance);
}
if (Balance <= 0)
{
printf("Sorry you are out of money!");
exit(0);
}
do
{
ValidBet = 0;
printf("\nPlease enter your bet:");
scanf("%lf", &Bet);
if ((Bet > Balance) || (Bet < 0))
{
printf("Your bet is invalid, try again.");
}
else
{
ValidBet = 1;
}
} while (ValidBet == 0);
ThrowDicePair();
printf("DICE #1 WAS %d", SumOfThrows);
if (SumOfThrows == 7 || SumOfThrows == 11)
{
Balance += Bet;
printf("You win! Would you like to play again? [y/n]");
C = getch();
if (C == 'y')
{
FirstRun++;
/* goto START; removed */
}
else if (C == 'n')
{
printf("Thanks for playing");
exit(0);
}
else /* ADDED */
return 0; /* ADDED */
}
else /* ADDED */
return 0; /* ADDED */
} /* ADDED */
}
在更复杂/嵌套的情况下,您可以使用continue重新循环,但在这里这是没用的
推荐阅读
- r - 每当在 R 中调用时自动递增的函数
- css - 为什么我在 Django 中收到我的 CSS 文件的“加载资源失败:服务器响应状态为 404 ()”?
- javascript - recharts 只为一个垂直点提供工具提示?
- windows - webHDFS curl --negotiate 在 Windows 上
- jquery - 如何在表格内设置复选框以选中
- tensorflow - pyTorch 中 tensorflow 的时间分布等价物
- php - Docker Nginx,php 不断重启
- c# - 从 Visual Studio 自动授予 UWP 应用权限
- javascript - 如何使用 Radio.Group Antd 设置检查?
- r - 在来自外部查找表的日期之间变化