我已经研究了其他类似的主题,但仍然无法找出我的代码有什么问题。以下是我的程序中的一个函数,用于查找数组的平均值。我在标题中得到了错误:错误:"I"的名称查找已更改为ISO的"scopeing"。以下是注意:如果您使用"-fpermisize"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;
}
想法和解释会很好,这样我就可以理解我到底做错了什么:/
for (int i = 0; i < ArrayLength; i++)
当您像这样在for
标头中定义i
时,它的作用域在for
循环中。不能像代码中的Mean = Sum / Array[i];
那样在for
循环之外使用它。
更改为:
int i;
for (i = 0; i < ArrayLength; i++)
还要注意,您永远不会初始化Sum
。
此语句
平均值=总和/数组[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;
}
所有提到的注释都是指您的代码。我已经纠正了。看看。
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;
}