c中的网格和指针

问题描述 投票:2回答:1

我在C中创建了这个程序,其中一个对象R被放置在一个网格上,并且它应该从它们的键盘输入。例如,如果按N键会发生这种情况。

         0 1 2
       0 - - -                      R - -                  - - -                               
       1 R - -  PRESS N -> GO UP -> - - - PRESS N AGAIN -> - - -
       2 - - -                      - - -                  R - -

所以R让它上升。物体必须四处移动,所以当它在[A0] [B0]时,它需要一直向下[A2] [B0]。往上看。它将向上,向下,向左和向右移动。

现在我正在创建让它向上移动的功能,但是我遇到了很多麻烦:有时候它会随机冻结到2:0和0:0而不会出现问题,当它在A = 2时,而不是上升到1,它变为0,虽然我将它设置为2-1(上升它必须减去1)。

我不明白是什么导致了这些麻烦,有什么建议吗?

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


#define X 3
#define Y 3

struct coords{
    int a;
    int b;
};

typedef struct coords cord;

// Print the array
char printArray(char row[][Y], size_t one, size_t two, struct coords cord)
{  

   row[cord.a][cord.b] = 'X';


   // output column heads
   printf("%s", "       [0]  [1]  [2]");
   // output the row in tabular format
   for (size_t i = 0; i < one; ++i) {

      printf("\nrow[%lu] ", i);

      for (size_t j = 0; j < two; ++j) {
         printf("%-5c", row[i][j]);
      } 
   } 
} 


int moveUp(struct coords * cord);


int main(void)
{  
   struct coords cord;


   char row[X][Y] =  
      { { '-', '-', '-'},
        { '-', '-', '-'},
        { '-', '-', '-'} };


   srand(time(NULL));


   cord.a = (rand() % 3); 
   cord.b = (rand() % 3);
   printf("\nValori rand: A %d, B %d\n", cord.a, cord.b);

   // output the row

   //printf("\nrobot:%c\n", robot);
   puts("The array is:");
   printf("\n");

   printArray(row, X, Y, cord);
   row[cord.a][cord.b] = '-';


   //printArray(row, X, Y, &m, &n);
   char h;

   while(h != '3'){


    switch (h) {

      case 'N':

        moveUp(&cord);
        printArray(row, X, Y, cord);
        row[cord.a][cord.b] = '-';

        break;
    }
    scanf("%s", &h);

  }

  printf("\n");
}

int moveUp(struct coords * cord)
{

   cord->a - 1;


   if (cord->a == 2){
      cord->a - 1;
   } else if (cord->a == 1){
      cord->a - 1;
   } else if (cord->a == 0){
      cord->a + 2;
   }



   /*
   if (cord->a == 0) {
    cord-> a = 2;
   } else {
    cord->a - 1;
   }
   */

   printf("\n A = %d, B = %d\n", cord->a, cord->b);



}
c pointers grid
1个回答
1
投票

在下面的代码中,您在读取任何内容之前检查h的值。如果h的未初始化值恰好是3,那么执行将不会进入while循环。

   char h;
   while(h != '3')

所以读入h中的值,然后在while循环中进行检查。

moveUp函数中,您可以使用ternary conditional运算符指定下一个位置或对象R

cord->a = (cord->a)? (cord->a - 1): 2;
© www.soinside.com 2019 - 2024. All rights reserved.