c - 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);
}
解决方案
在下面的代码中,您h
在读取任何内容之前检查它的值。如果未初始化的值h
恰好是3
,则执行不会进入while循环。
char h;
while(h != '3')
所以读入一个值h
,然后在while
循环中进行检查。
在moveUp
函数中,您可以使用三元条件运算符来分配下一个位置或对象R
。
cord->a = (cord->a)? (cord->a - 1): 2;
推荐阅读
- reactjs - 不显示空状态
- swift - Swift Codable:不同的编码/编码策略
- rust - 包含原始指针的结构可以实现 Send 并且是 FFI 安全的吗?
- nested - 包括多个嵌套关系的联盟分形
- peoplesoft - 为什么要在 AWE 中使用 Route Controls 而不是 Steps
- oracle - 如何使用 DBMS_STATS.set_table_prefs 将具有相同所有者的多个表的 Incemental 设置为 true?
- babeljs - 在 Ubuntu 16.0.4 上安装 Babel
- bash - 如何回显某些内容并读取用户输入,然后在同一行上回显某些内容?
- android - Android NDK突然很慢
- c++ - 使用宏定义打印格式参数