【问题标题】:Nested For Loop Variable Increment嵌套 For 循环变量增量
【发布时间】:2018-12-25 13:00:00
【问题描述】:

我有一个文本框,显示由软件编辑的草图,变量动态更改。

https://cdn.discordapp.com/attachments/398780553731506176/468835565304020995/unknown.png

但是对于buttons数组,我需要使用一些for循环来写数字

格式需要是这样的

byte buttons[NUMROWS][NUMCOLS] = { {0,1,2,3,4,}, {5,6,7,8,9,}, {10,11,12,13,14,},

但到目前为止我能做到的只有

byte buttons[NUMROWS][NUMCOLS] = { {0,1,2,3,4,}, {1,2,3,4,5,}, {2,3,4,5,6,},

我需要推进循环以增加数字。我正在使用两个嵌套的 for 循环

        int i;
        for(int x = 0; x < rows; x++) //row
        {
            string buttonbyte = "{";
            for (i = x; i < columns + x; i++) //column
            {
                buttonbyte += i;
                buttonbyte += ",";
            }
            sketch[9 + x] = buttonbyte + "},";
        }

该代码用于编辑 arduino .ide 草图并上传它的程序,以便于使用。

任何帮助将不胜感激!

干杯, 摩根

【问题讨论】:

  • 你能用 List 代替数组吗?
  • 我不确定,它是用于键盘库的。它需要使用二维数组。

标签: c# loops for-loop nested increment


【解决方案1】:

如果跳跃总是这样,你只需要做到这一点

 int i;
        for(int x = 0; x < rows; x++) //row
        {
            string buttonbyte = "{";
            for (i = 0; i < columns; i++) //column
            {
                buttonbyte += (i + columns*x); // column + columns * row
                buttonbyte += ",";
            }
            sketch[9 + x] = buttonbyte + "},";
        }

PS:这可能不起作用,因为我现在没有编译器,您可能需要将 (i + columns*x) 转换为字符串

【讨论】:

  • 是的,可以,但是这个数字太高了。输出类似于 {0,1,2,3,4,}, {6,7,8,9,10,}, {12,13,14,15,16,},
  • 让我每次都从零开始。
  • 您需要重写第二个循环才能使该循环不包含 X,如果您使用(i + 列 * x)
  • 是的,我刚刚注意到……我的错。手头没有编译器的问题
【解决方案2】:

我认为你的第二个循环需要

for (i = (x * columns); i < ((x + 1) * columns); i++)

第一次迭代为 0,1,2,3,4,第二次为 5,6,7,8,9,依此类推。

【讨论】:

  • 这意味着比我的解决方案@MorGuux 使用的更改更少
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 2017-03-22
相关资源
最近更新 更多