首页 > 解决方案 > c中的网格和指针

问题描述

我用 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);



}

标签: cpointersgrid

解决方案


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

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

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

moveUp函数中,您可以使用三元条件运算符来分配下一个位置或对象R

cord->a = (cord->a)? (cord->a - 1): 2;

推荐阅读