如何在空数组中移动一个值

时间:2018-02-18 04:23:42

标签: c arduino

我希望能够拥有一个角色' 0'在15个空格数组的末尾向左移动到数组的开头,然后返回到数组的末尾并重复。这就是我到目前为止所得到的......

#include<stdio.h>

void printArray(int array[]) {
  for (int i = 0; i < 20; i++) {
    printf("%d ", array[i]);
  }
}

int main(void) {
  int a [15] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '0'};
  int scrollLeft;
  printArray(a);
  int i = 0;
  while (i = 0) {
    printArray(a);
    scrollLeft = a[15] - 1;
  }
}

用C语言编写,我希望能够在我的Arduino上为游戏实现此代码。如果有人可以告诉我我做错了什么就会很棒!

谢谢, Ezrelle

1 个答案:

答案 0 :(得分:2)

您的代码存在许多问题,其中一些我在这里评论过。我鼓励您阅读一些文献以熟悉C语言。在没有太多经验的情况下编写C代码会让人感到沮丧,特别是如果您甚至不确定自己的工作开始时间。

#include <stdio.h>


/*
    changed this function to take a length argument
    which will probably stop runtime errors with your version
    and added print for a newline at the end so that the lines dont pile up.
    could change that to a \r which would overwrite the line
*/
void printArray(char array[], int length)
{
    for(int i = 0; i < length; i++) // changed to use new length variable
    {
        printf("%c ", array[i]); // changed this to %c to print characters
    }

    printf("\n");
}

/* 
    added this function which shifts the contents of the array.
    take a look at what it does, and try to understand why the temp variable is needed
*/
void scrollLeft(char array[], int length) {
    int temp = array[0];
    for(int i = 0; i < length-1; i++)
    {
        array[i] = array[i+1];
    }
    array[length-1] = temp;
}

int main(void)
{
    /* 
        this array should be of type char because you're assigning it with character values
        changed this so that the array is initialized with the proper size
        and added the length variable to store how long the a is
    */
    char a [16] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '0'};
    int length = 16;

    printArray(a, length);

    int i = 0;

    /*  changed from i = 0 to proper i == 0
        i = 0 assigns i to be equal to zero
        i == 0 checks to see if i is equal to zero
    */
    while (i == 0) 
    {
        printArray(a, length);
        scrollLeft(a, length);
    }
 }

如果你想创建一些自己的优化,有一些方法可以让这段代码运行得更快,因为我写的scrollLeft代码并没有考虑到数组只有一个{{1所有其他元素都是'0'