我被分配设置一个带点的数组.我被告知获得最大值,平均值,并且在同一个数组中,如果数组中的任何点是平均值的两倍,我应该cout是"异常值".到目前为止,我已经获得了数组中的平均数和最大数.但我无法将程序设置cout为异常值.相反,它给了我平均值的倍数.这是程序;
int main()
{
const int max = 10;
int ary[max]={4, 32, 9, 7, 14, 12, 13, 17, 19, 18};
int i,maxv;
double out,sum=0;
double av;
maxv= ary[0];
for(i=0; i<max; i++)
{
if(maxv<ary[i])
maxv= ary[i];
}
cout<<"maximum value: "<<maxv<<endl;
for(i=0; i<max; i++)
{
sum = sum + ary[i];
av = sum / max;
}
cout<<"average: "<<av<<endl;
out = av * 2;
if(ary[i]>out)
{
cout<<"outlier: "<<maxv<<endl;
}
else
{
cout<<"ok"<<endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Ste*_*art 10
您的代码包含一个微妙而棘手的错误.你在最后的for循环之后使用ary [i].此时,i的值等于max,因此if语句比较随机内存,因为你要离开数组的末尾.
由于这是C++而不是C,你可以通过像这样在for循环中声明循环变量来避免这个特定的错误
for (int i = 0; i < max; ++i) {
....
}
Run Code Online (Sandbox Code Playgroud)
您需要使用两个 for 循环。然后,您应该遍历ary并检查每个元素。outcout << ary[i]
如果您在使用变量的地方(在可能的最小范围内)声明变量,这可能会更明显一些。
例如:
for (int i = 0; ...) {
}
Run Code Online (Sandbox Code Playgroud)
和
double outlier = avg * 2;
Run Code Online (Sandbox Code Playgroud)
顺便说一句,这可能有点难以理解(现在),但 STL 提供了用于确定数组的max (max_element)和sum (accumulate)的函数。读起来可能很有趣。