【问题标题】:for loop in C returning only first value of arrayC中的for循环仅返回数组的第一个值
【发布时间】:2012-11-25 14:10:17
【问题描述】:

我是初学者。好吧,我只是在尝试数据结构,但不明白为什么会出现错误。我认为发布代码和我得到的输出会更好。 (我使用 C-Free 4.0 编译器),顺便说一下。这是代码

// 编写一个C程序来输入和显示数组的元素

    #include <stdio.h>
    int main(int argc, char *argv[])
{
    int a[44],n,i=0;
    // No. of elements:
    printf("\n How many elements in all?");
    scanf("%d",&n);

    // Entering all elements:
    printf("\n\n Plz do enter the elements:");
    for(;i<n;i++)
    scanf("%d",&a[i]);

    // Displaying all elements:
    printf("\n Array elements are:");

     for(i=0;i<n;)
     {

       printf("\n a[%d]=%d",i,a[i]);
       i++;
       break;

     }

    int sum=0;
    for(i=0;i<n;i++)

    {
      sum=sum+a[i];

    }

    printf("\nSum=%d",sum);


    return 0;
}
/*
  And here's the output when I say that I'm entering 3 elements into the array:

   How many elements in all?3


 Plz do enter the elements:12
0
-22

 Array elements are:
 a[0]=12
Sum=-10Press any key to continue . . . */

正如你们所见,我可以输入值 for(i=0;i

【问题讨论】:

    标签: c arrays loops for-loop


    【解决方案1】:
    for(i=0;i<n;)
    {
       printf("\n a[%d]=%d",i,a[i]);
       i++;
       break;
    }
    

    你放了一个break;,所以它只打印1个元素。

    删除break;,它将全部打印出来。

    您也可以将i++ 放在条件i&lt;n 旁边,如下所示。

    for(i=0;i<n;i++)
    {
        printf("\n a[%d]=%d",i,a[i]);
    }
    

    【讨论】:

      【解决方案2】:

      for()循环有两种使用方式,

      for (Start value; end condition; increase value)
              statement;
      

      Start value = initialization;
      for (; end condition;){
              statement;
              increase value;
      }
      

      在您的代码中,Start 值被初始化为 i = 0,因此您可以尝试任何方法,但为了方便和清晰,最好首先接受更多。

      【讨论】:

        【解决方案3】:
        for(i=0;i<n;)
        {
           printf("\n a[%d]=%d",i,a[i]);
           i++;
           break;
        }
        

        您正在使用的 break 语句让您跳出循环。 删除 break 语句,它将打印数组的所有元素....

        【讨论】:

          猜你喜欢
          • 2018-03-09
          • 1970-01-01
          • 2022-12-15
          • 2020-06-01
          • 1970-01-01
          • 2023-03-03
          • 2023-03-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多