gpt4 book ai didi

c - 如何使空数组中的一个值左移

转载 作者:行者123 更新时间:2023-11-30 18:47:24 26 4
gpt4 key购买 nike

我希望能够在 15 个空格的数组末尾有一个字符“0”,以左移到数组的开头,然后返回到数组的末尾并重复。这就是我到目前为止所得到的...

#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 上为游戏实现此代码。如果有人可以教我做错了什么,那就太好了!

谢谢,埃兹雷尔

最佳答案

您的代码存在许多问题,我已在此处评论了其中一些问题。我鼓励您阅读一些文献来熟悉 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代码没有考虑到数组只有一个'0 ' 且所有其他元素均为 ' '

关于c - 如何使空数组中的一个值左移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48848435/

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