【问题标题】:Lego Mindstorms NXT, NXC: Error in replacing elements in an array (no matter the dimension)Lego Mindstorms NXT、NXC:替换数组中的元素时出错(无论维度如何)
【发布时间】:2019-12-21 21:21:09
【问题描述】:

我尝试使用 Bricx 指挥中心Lego Mindstorms NXT 积木写一个简单的十五拼图。但总是有同样的问题。数组的元素(无论维度)第二次都不会改变。

这是模拟错误的代码。如果您没有 NXC 块来检查它,程序会输出一个 4x4 的零网格(没关系),然后程序以“文件错误!”退出。在 LCD 屏幕上,大概是在尝试将数组的第一个零元素更改为 1 时。

如果您有任何想法,请告诉我。我认为 NXC 语言并不是为了以这种特殊方式处理数组而开发的,尽管我觉得它很奇怪。

附:我也尝试使用内置函数 ArrayReplace() 但没有成功。

代码示例如下:

int count;
int numMatrix[] = {1, 2 ,3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 69};
const int xcoord[] = {12, 37, 62, 87};
const int ycoord[] = {56, 40, 24, 8};

void fillGrid(){
     int j, k;
     for (int i = 0; i < 16; i++){
         numMatrix[i] = count;
         if (k == 4){
            k = 0;
            j++;
         }
         NumOut(xcoord[j], ycoord[k], numMatrix[i]);
         Wait(50);
         k++;
         }
     Wait(2000);
     ClearScreen();
}

task main(){
     while (true){
           fillGrid();
           count++;
     }
}

好吧,这显然是我的错,我应该初始化 j 和 k 局部变量并将它们等于 0。现在看看我尝试对二维数组执行相同操作的情况。

#define NROWS    4
#define NCOLUMNS 4

int count;
int numMatrix[NROWS][NCOLUMNS] = {
    { 1,  2,  3,  4},
    { 5,  6,  7,  8},
    { 9, 10, 11, 12},
    {13, 14, 15, 69} };
const int xcoord[] = {12, 37, 62, 87};
const int ycoord[] = {56, 40, 24, 8};

void fillGrid(){
     for (int i = 0; i < NROWS; i++){
         for (int j = 0; j < NCOLUMNS; j++){
             numMatrix[j][i] = count;
             NumOut(xcoord[i], ycoord[j], numMatrix[j][i]);
             Wait(50);
         }
     }
     Wait(2000);
     ClearScreen();
}

task main(){
     while (true){
           fillGrid();
           count++;
     }
}

没有什么会改变数组的所有元素都将保持与它们初始化时的相同(1、2、3...)。现在越来越有趣了。。

【问题讨论】:

  • 第一次循环时jk 的值是多少?
  • 初始化时,它们都是0。
  • 如果它们是像count 这样的文件范围,它们将为零,但ij 是本地的,所以在堆栈上找到任何随机值。显式初始化它们。
  • 你完全正确!我的错。
  • 发布的代码将导致 15 个 0 的矩阵,然后是 15 个 1 的矩阵,...然后是 15 个 15 秒的矩阵,然后是 15 个 16 秒的矩阵 .... 直到 15 个最大整数然后显示的下一个值未定义。建议main(): count++; 中的行后面跟着行:count = count %16;

标签: c arrays lego mindstorms nxc


【解决方案1】:

问题是:在C语言中,局部变量是在栈上分配的,默认情况下没有为你初始化,你必须自己做。

int count;               // global: automatically initialized to zero

void fillGrid() {
     int j = 0, k = 0;   // local: NOT automatically initialize - you do it.

     for (int i = 0; i < 16; i++){
         numMatrix[i] = count;
         if (k == 4){
            k = 0;
            j++;
         }
         NumOut(xcoord[j], ycoord[k], numMatrix[i]);
         Wait(50);
         k++;
     }
    ...
}

如果您没有初始化它们,无论堆栈中发生什么,您都会得到随机垃圾:在我的系统上,j 恰好为零,但 k 是 4195392。

我认为 NXC 语言不是为了以这种特定方式处理数组而开发的

这实际上与它没有任何关系:库代码(例如,NumOut)永远不会看到数组,只有从数组索引并单独传递给库的单个值。

【讨论】:

  • 我已经编辑了问题,您现在可以查看描述的问题。
猜你喜欢
  • 2014-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多