gpt4 book ai didi

c - 我如何避免在这里使用 goto 语句?

转载 作者:行者123 更新时间:2023-12-04 11:39:00 26 4
gpt4 key购买 nike

我是 C 语言编程的新手,我正在制作一个简单的基于骰子的游戏。我有所有其他逻辑工作,但我无法看到如何避免 goto 语句。基本上,玩家以 50 美元作为余额开始,程序要求下注,然后掷骰子,根据掷骰的结果,会发生不同的事情。主要问题是当结果发生时,系统会询问用户是否要再次玩,如果他们说不,我就退出,但如果他们说是,我需要回到开始并再次要求下注。


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 来重新循环,但在这里这是无用的

关于c - 我如何避免在这里使用 goto 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55382865/

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