问题
I have looked at other topics similar to this and still cannot find out what is wrong with my code. The following is a function in my program to find the Mean (Average) of Arrays. I get the error in the title: error: name lookup of 'i" changed for ISO 'for' scoping. following with note: if you use '-fpermissize' g++ will accept your code.
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;
}
Ideas and explanation would be lovely so I can understand what the hell I'm doing wrong :/
回答1:
for (int i = 0; i < ArrayLength; i++)
When you define i
in the for
header like this, its scope is inside the for
loop. You can't use it outside the for
loop like Mean = Sum / Array[i];
in your code.
Change it to:
int i;
for (i = 0; i < ArrayLength; i++)
Also note you never initialize Sum
.
回答2:
This statement
Mean = Sum / Array[i];
makes no sense.
As for the error then you are trying to use varaible i in expression Array[i] in the statement above outside its scope. It is defined only within the loop.
Also you forgot to initialize variable Sum and I think it should have type double.
The function could look like
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;
}
来源:https://stackoverflow.com/questions/26552165/error-name-lookup-of-i-changed-for-iso-for-scoping