【问题标题】:error: name lookup of 'i' changed for ISO 'for' scoping错误:“i”的名称查找已更改为 ISO“for”范围
【发布时间】:2014-12-20 13:00:49
【问题描述】:

我查看了与此类似的其他主题,但仍然无法找出我的代码有什么问题。以下是我的程序中查找数组的平均值(平均值)的函数。我在标题中收到错误:错误:“i”的名称查找已更改为 ISO 'for' 范围。以下注意:如果您使用 '-fpermissize',g++ 将接受您的代码。

double GetMean ( double Array[], int ArrayLength )
{
    int Sum, Mean;
    for ( int i = 0; i < ArrayLength; i++ )
    {
         Sum = Sum + Array[i];
    }

    Mean = Sum / Array[i];

    return Mean;
}

想法和解释会很可爱,所以我可以理解我到底做错了什么:/

【问题讨论】:

    标签: c++ arrays function average mean


    【解决方案1】:
    for (int i = 0; i < ArrayLength; i++)
    

    当您像这样在for 标头中定义i 时,它的范围在for 循环内。您不能在代码中的 for 循环之外使用它,例如 Mean = Sum / Array[i];

    改成:

    int i;
    for (i = 0; i < ArrayLength; i++)
    

    还请注意,您从不初始化 Sum

    【讨论】:

    • 非常感谢。让我感到沮丧的是,只是那条小线导致了这么大的问题。
    【解决方案2】:

    此声明

    平均值 = Sum / Array[i];

    没有意义。

    至于错误,那么您试图在其范围之外的上述语句中的表达式 Array[i] 中使用变量 i。它仅在循环内定义。

    另外你忘了初始化变量 Sum,我认为它应该是 double 类型。

    函数可能看起来像

    double GetMean( const double Array[], int ArrayLength )
    {
        double  Sum = 0.0;
    
        for ( int i = 0; i < ArrayLength; i++ )
        {
             Sum = Sum + Array[i];
        }
    
        return ArrayLength == 0 ? 0.0 : Sum / ArrayLength;
    }
    

    【讨论】:

      【解决方案3】:

      所有提到的 cmets 都是指您的代码。 我已经纠正了。看看吧。

      double GetMean ( double Array[], int ArrayLength )
      {
          int i;
          double Mean,Sum=0;                                //You must initialise Sum=0 and you should declare Mean and Sum as double otherwise your calculated mean would always come out to be an integer 
          for (i = 0; i < ArrayLength; i++ )         //The variable i has scope within the loop only in your case. To use it outside the loop you should declare it outside and before the loop
          {
               Sum = Sum + Array[i];
          }
      
          Mean = Sum /i;                        //Logical error Mean=(sum of terms)/(Number of terms). You will get unexpected output from your logic.  
      
          return Mean;
      }
      

      【讨论】:

        猜你喜欢
        • 2013-06-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多