【问题标题】:How to invert the elements of an array?如何反转数组的元素?
【发布时间】:2017-03-04 06:41:35
【问题描述】:

我是 C 编程的初学者。我试图编写代码来反转数组的元素。这是我写的

#include <stdio.h>
int main(void)
{
    int a[5], i, j, b[5], k=5;
    printf("enter 5 numbers");
    for (i=0;i<5;i++)
    {
        scanf("%d",&a[i]);
    }

    for(i=1;i<5;i++)
    {
        for(j=k; j>=1; j--)
        {
            b[j] = a[i];
            k--;
            break;
        }
    }

    for(j=1; j<5; j++)
    {
        printf("%d\n",b[j]);
    }
    return 0;
}

在输出中,我只得到 3 个反转的数字,而不是全部 5 个。 谁能帮帮我?

【问题讨论】:

  • Emmm...你不应该先单独存储元素吗?
  • 对不起,我没有得到你!我的意思是我用过 scanf ,对吧?
  • 嗯。忽略它。缩进搞砸了。

标签: c arrays loops for-loop


【解决方案1】:

您实际上并不需要循环内的循环。只需一个即可轻松完成:

for(i=0; i<5; i++)
{
    b[i] = a[4-i];
}

【讨论】:

    【解决方案2】:

    首先,数组索引从0 开始,而不是从1。因此,如果您声明大小为 4 的数组,则有效索引是从 0 到 3。要更清楚地理解这一点,请参阅 https://www.tutorialspoint.com/cprogramming/c_arrays.htm

    现在您要做的事情只能通过单循环来完成!像这样:

    #include <stdio.h>
    int main(void) {
        int a[5],i,j,b[5],k=5;
        printf("enter 5 numbers");
        for(i=0;i<5;i++)
        {
            scanf("%d",&a[i]);
        }
    
        //see this :
        for(i=0;i<5;i++)// runs from 0 to 4
        {
            int bIndex = 4 - i;//get index of array b to store element of array a
            b[bIndex] = a[i];
        }
    
        for(j=0;j<5;j++)
        {
            printf("%d\n",b[j]);
        }
        return 0;
    }
    

    【讨论】:

      【解决方案3】:
      #include <stdio.h>
      int main(void)
      {
          int a[5], i, j, b[5], k=5;
          printf("enter 5 numbers");
          for (i=0;i<5;i++)
          {
              scanf("%d",&a[i]);
          }
          `for(i=0;i<5;i++)`//see here begin
          {
             `for(j=5-k; j>=0; j++)` 
              {
                  b[j] = a[i];
                  k--;
                  break;
              }
          }
          `for(j=0; j<5; j++)`
          {
              printf("%d\n",b[j]);
          }
          return 0;
      }
      

      【讨论】:

        【解决方案4】:

        我相信,你的第一个问题是循环条件写成

          for(j=k; j>=1; j--)
        

        您使用j 进行索引的位置。这使得b[j] 相差一个。你应该把它改成

          for(j=k-1; j >= 0; j--)
        

        也就是说,

                k--;
                break;
        

        里面的循环也是错误的。实际上你不需要两个循环。简化如下。

         for(i=k-1, j =0; j < k; j++, i--)  //j goes up, i goes down.
         {
             b[j] = a[i];
         }
        
         for(j=0; j<5; j++)               //j starts from 0.....
         {
            printf("%d\n",b[j]);
         }
        

        【讨论】:

        • 感谢您的回答.....但我仍然只得到倒数而不是 5
        • 不需要这一切。看看eyalm的回答。如此简单。
        • @TonyTannous 和我决定改变我的数组大小并且程序崩溃了...... :)
        猜你喜欢
        • 1970-01-01
        • 2021-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多