gpt4 book ai didi

c - 因子博弈,使用循环

转载 作者:太空宇宙 更新时间:2023-11-04 04:38:49 25 4
gpt4 key购买 nike

所以我正在创建一个程序,其中一个数字将由 2 位用户进行因式分解,并且在不使用原始数字的情况下将其分解为 1 的人获胜。我应该使用循环,但我不知道哪个是最好的,也不知道如何构造它,才不会像我的大多数程序那样令人费解。

在文本中,它的结构应该是这样的。

输入一个数字 N 作为要因式分解的数字。 2 玩家将轮流输入一个数字来分解 N 倍。因数不能小于2,必须均分N。

  • 输入8。
  • 玩家 1 输入一个因素。
  • 玩家 1 输入 4。
  • N 现在是 8/4。
  • 玩家 2 输入一个因素。
  • 玩家 2 输入 2。
  • N 现在是 8/4/2。
  • N 现在是 1。玩家 2 赢了!

程序应该循环这个循环,每次向每个玩家 1 询问一个新号码,直到号码为 1。我现在将发布我的代码,我不确定如何继续,或者我是否正在使用右循环,因为 while 通常用于以条件为假为前提的语句。

#include <stdio.h>


int main(){

int gameN;
int factor;



printf("What number should the game be played with?\n");
scanf("%d", &gameN);



while (gameN != 1) {
{

printf("The current number is %d .Current Player enter a factor.\n", gameN);
scanf("%d", &factor);

if (gameN%factor==0){
printf("the current number is %d . Current Player enter a factor.\n");
scanf("%d", &factor);

if (gameN/factor== 1){
break; printf("Game Over. You won!");
}
if (factor<2) {
printf(" Invalid Factor. Numbers less than 2 are not allowed. The current number is %d. Current Player, enter a factor.\n", gameN);
scanf("%d", &factor);


return 0;

感谢任何人的帮助。

最佳答案

scanf("%d", &factor); 之后可能会发生三件坏事

  • 用户没有输入数字
  • 数字不分为gameN
  • 因子小于2

在每种情况下,您都希望继续 循环。 C 中的 continue 语句导致循环从顶部重新开始。

作为旁注,您可以检查 scanf 的返回值以确保 scanf 有效。它将返回成功转换的次数,在您的代码中应该为 1。

以下代码显示了如何使用continue 语句重新启动循环,直到用户输入有效数字。它还展示了如何刷新输入,以防用户输入垃圾,如“fdajkl”。

#include <stdio.h>
#include <stdlib.h>

int main( void )
{
int gameN, factor, count;

printf( "What number should the game be played with?\n" );
if ( scanf( "%d", &gameN ) != 1 )
exit(1); // user didn't enter a valid number, so just quit

while ( gameN != 1 )
{
// get a factor from the user
printf("The current number is %d. Current Player enter a factor.\n", gameN);
count = scanf( "%d", &factor );

// check for all the bad things that can happen
if (count != 1 || gameN % factor != 0 || factor < 2 )
{
scanf( "%*[^\n]" ); // read and discard any characters up to the newline
getchar(); // read and discard the newline character
printf( "That's not a valid input\n" ); // notify the user
continue; // go back to the top of the loop to try again
}

gameN /= factor; // divide the game value by the factor

if ( gameN == 1 ) // check for victory
{
printf( "Game Over. You won!\n" );
break;
}
}

return 0;
}

关于c - 因子博弈,使用循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28491273/

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