1

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

这是播放器 2 先行的时候,它工作正常

这是当玩家 1 先走并且它只重复一次

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;

}
4

2 回答 2

1

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

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

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

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

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

于 2013-04-09T02:40:39.280 回答
0

你的代码中有一个无限循环,

你下面给出的代码是错误的,

   while(playerNumber != playerInput)
   {

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

   }

它应该是,

   if(playerNumber != playerInput)
   {

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

   }
于 2013-04-09T02:34:22.157 回答