gpt4 book ai didi

c - 两名玩家的猜数游戏

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

谁能帮我弄清楚我的程序出了什么问题,这对我来说很复杂。这是一个数字猜谜游戏,两个玩家可以玩。首先说哪个玩家先走,然后玩家必须输入他的数字 1 或 2,然后输入猜测或传球(玩家不能连续传球超过 3 次或两次)。它工作得非常好,除了每次玩家 1 开始时它连续两次要求他猜测然后工作正常,当玩家 2 开始时它交替像它应该是这样的:

Here is when player 2 goes first it works fine

Here it is when player 1 goes first and it reapeats only once

And this is my code It quite a lot of code:

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

int main(void) {

int playerNumber = 0;
int number = 0;
int playerInput = 0;
int guess = 0;
char input;
char str[6] = {0};
int playerA = 1;
int playerB = 2;
int passA = 3;
int passB = 3;
int i = 1;
int playerTurn = 0;
int turn = 0;

srand(time(NULL));
playerNumber = 1 + rand() % 2; /* Random number is generated */

srand(time(NULL));
number = 0 + rand() % 100; /* Random number is generated */


while(number != guess) {

printf("\nIt's player's %d turn\n", playerNumber);

printf("Player Number?\n");

scanf("%d", &playerInput);

while (playerNumber != playerInput)
{

printf("You Have to wait your turn.\nPlayer number?\n");

}

if (playerA != playerNumber)
playerB = playerNumber;

if (i%2 == 1) {
playerNumber = playerA;
}
else {
playerNumber = playerB;
}

i = i+1;

printf("Enter Your Guess, 0 - 100 or Pass: ");

scanf("%s", str);


if (strcmp(str, "pass") == 0){
if (playerNumber == playerA){
passB = passB -1;
printf("Player 2 has %d more 'Pass' left!\n", passB);
}
else{
passA = passA -1;
printf("Player 1 has %d more 'Pass' left!\n", passA);
}
}
else {
guess = atoi(str);
if(guess < number) /* if the guess is lower, output: the guess is to low */
printf("Your guess was to low.\n ");

else if(guess > number) /* if the guess is higher, output: the guess is to high */
printf("Your guess was to high.\n ");

else /* is the guess is equial to the random number: Success!! */
printf("Yes!! you got it!\n");

}

}
return 0;

}

最佳答案

首先,你应该使用一致的缩进。这将使您更容易阅读您的代码。

其次,您应该使用换行符和空格将相似的行组合在一起。将编写代码想象成写散文,将换行符视为分隔段落的方式。您几乎不会对任何内容进行双倍行距,因为它会浪费空间并且更难阅读(人们不习惯),所以不要对您的代码进行双倍行距。

第三,您对 playerA 和 playerB 变量的使用是一个不错的概念,但还有更好的方法来实现。 C/C++ 中的典型约定是对魔数(Magic Number)使用#define,全部大写 - #define PLAYER_A 1。遵循此约定将使您的代码更具可读性。此外,由于您的玩家是“1”和“2”,因此使用 #define PLAYER1 1 或 PLAYER_1 更具可读性。

您使用变量“i”,但使用名为 i、j、k、m 或 n 的变量的约定是作为循环计数器,在循环顶部或循环底部递增。在循环中间增加循环计数器会使计数器更容易丢失。将增量移动到顶部或底部。

手动完成工作以查看程序执行时的变量。你的老师已经在类里面这样做了。只需写下每个变量并在其旁边写下它的值,然后更改变量,因为它们会在程序执行时发生变化。这项技术将帮助您在未来修复其他棘手的错误,而不是我给您答案。

关于c - 两名玩家的猜数游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15892244/

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