how many times does the user want to play a game c language
我正在学习如何编写游戏,并已获得游戏的以下规则。
- 规则1:玩家必须定义一个最小数字才能停止转弯,该数字必须大于10
- 规则2:所有回合都加到总数中
- 规则3:如果骰子落在1上,则该回合的所有点数都将被没收
- 规则4:第一个获得101分的玩家获得胜利!
我试图在用户输入有多少个玩家之后获取要输入的游戏数量。
我的问题是,每次我输入玩家名称时都会询问用户,具体取决于我输入了多少玩家
示例
How many Players: 3
How many games: 15
Enter Players name: John
How many games: 15 (I input this number again) I dont need this line here
Enter Players name: Mary
How many games: 15 (I input this number again) I dont need this line here
Enter Players name: Barry
How many games: 15 (I input this number again) I dont need this line here
这是我针对该问题的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | //user inputs value of player_num, here, as you have now// printf_s("Please type in the number of players:"); scanf_s("%d", &player_num, sizeof(int)); for (i = 0; i < player_num; i++) { //user inputs value of num_game, here, as you have now// printf_s("Please type in the number of games:"); scanf_s("%d", &num_games, sizeof(int)); num_games = (j = 1, num_games); printf_s("Enter the player's first name:"); scanf_s("%s", names[i], 25); getchar(); } printf_s("\ "); for (i = 0; i < player_num; i++) printf_s("\ %s", names[i]); |
之所以不断要求您"输入游戏数",是因为您已将printf和scanf语句放入循环中。
1 2 3 4 5 6 7 8 9 | for (i = 0; i < player_num; i++) { printf_s("Please type in the number of games:");//this scanf_s("%d", &num_games, sizeof(int));//this num_games = (j = 1, num_games); //including this printf_s("Enter the player's first name:");// also this scanf_s("%s", names[i], 25); // and this getchar(); } |
由于这个原因,每次执行循环时,它都会要求您输入值。
相反,如果您希望它只问您一次,则如果要将语句仅执行一次,则必须将其置于循环之外。
您可以执行以下操作:
get the number of games to be inputted in after the user enters how
many players there are.
1 2 3 4 5 | printf_s("Please type in the number of players:"); scanf_s("%d", &player_num, sizeof(int)); printf_s("Please type in the number of games:"); scanf_s("%d", &num_games, sizeof(int)); num_games = (j = 1, num_games); |
它是
asking the user every time you enter the players names depending on how
many players you have inputted
because you've entered those lines"inside the loop";
您的循环有2个
scanf_s("%d", &num_games, sizeof(int));
num_games = (j = 1, num_games);
在循环的前面,而不是在循环的内部。
1 2 3 4 5 6 7 8 9 10 11 12 | for (i = 0; i < player_num; i++) { //user inputs value of num_game, here, as you have now// printf_s("Please type in the number of games:"); // no need for this in the loop scanf_s("%d", &num_games, sizeof(int)); // no need for this in the loop num_games = (j = 1, num_games); // no need for this in the loop printf_s("Enter the player's first name:"); scanf_s("%s", names[i], 25); getchar(); } |