产生一个随机数组,并计算随机数组的均值和方差。代码如下:
#include<iostream>
#define N 100
using namespace std;
int main()
{
int randdata[N];
double sum=0;
double average;
double temp[N];
double variance=0;
cout<<"随机数:";
for(int i=0;i<N;i++)
{
randdata[i]=-5+rand()%11; //产生-5到5之间的随机数
cout<<" "<<randdata[i];
sum+=randdata[i];
}
cout<<endl;
average = sum/N; //计算均值
cout<<"均值:"<<average<<endl;
for(int j=0;j<N;j++)
{
temp[j]=(randdata[j]-average)*(randdata[j]-average);
variance+=temp[j];
}
variance=variance/N;
cout<<"方差:"<<variance<<endl; //计算均值
return 0;
}