【问题标题】:Is this the right way to access array elements?这是访问数组元素的正确方法吗?
【发布时间】:2020-07-10 08:26:26
【问题描述】:

我有一个填充了 1 和 0 的数组,还有两个 LED(1 = 左 LED / 0 = 右 LED)

int Game[100]

我有一个数组,用于编写用户操作(使用操纵杆)。 (( 这个数组的最初想法是不断地将它的大小增加一......但我读到你不能这样做,你需要实现一个“链接列表”,但现在,好吧。 ))

int Player[2]

我想遍历数组“Game”的所有元素,但只遍历一个元素

    int i;
    for(i = 0; i <= 100; i++) {
        if(Game[i] == 1) {
            // Left LED ON
            // Left LED OFF
        }
        else if (Game[i] == 0) {
            // Right LED ON
            // Right LED ON
        }

我的意思是,首先我想从数组中取出两个元素,打开 LED...等待用户输入... 然后取另一个元素(重复前两个),依此类推。有什么办法可以做到吗?

【问题讨论】:

  • 我不明白你在做什么。但是那个i &lt;= 100应该是i &lt; 100。
  • int Player[2]在其中的作用是什么?
  • this array was to constantly increase its size by one ... but I read that you can’t do this and you need to implement a “Linked list” :您可以使用realloc 调整在堆中分配的数组的大小,但是您的数组在这里的作用是什么?为什么你认为你需要调整它的大小?

标签: c for-loop led joystick


【解决方案1】:

我不确定您的确切动机是什么,但我想我可以帮助您根据用户输入一一访问这些元素。检查我的代码:(希望你找到有用的东西)

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int Game[100];
    int i,j=0;
    //filling each element with 1s and 0s
    for(i=0;i<100;i++)
    {
        if(i%2==0)
           Game[i]=0;
        else
           Game[1]=1;
     }
     i=0;
     printf("User Input(-1 to Quit): ");
     scanf("%d",&j);
     while(j!=-1 && i<100)
     {
         //your code
         if(Game[i] == 1)
         {
            // Left LED ON
            // Left LED OFF
         }
         else
         {
            // Right LED ON
            // Right LED ON
         }
         ++i;
         printf("Another User Input(-1 to quit): ");
         scanf("%d",&j);
    }
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-05
    • 2016-05-10
    相关资源
    最近更新 更多