gpt4 book ai didi

c - 乐高头脑 Storm NXT、NXC : Error in replacing elements in an array (no matter the dimension)

转载 作者:行者123 更新时间:2023-11-30 20:16:53 24 4
gpt4 key购买 nike

我尝试使用Bricx Command CenterLego Mindstorms NXT block 编写一个简单的十五个谜题。但总是有同样的问题。数组的元素(无论维度)第二次不会改变。

这是模拟错误的代码。如果您没有 NXC block 来检查它,程序会输出 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...)。现在变得更有趣了..

最佳答案

问题是:在 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。

I presume that NXC language wasn't developed to work with arrays in that particular way

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

关于c - 乐高头脑 Storm NXT、NXC : Error in replacing elements in an array (no matter the dimension),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59439923/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com