c++如何把数输入到一维数组中,并求均方差

2025-05-15 06:22:47
推荐回答(2个)
回答1:

可以用这个,希望能帮到你
#include
#include
using namespace std;
int main()
{
const int size = 100;//如果想加大数组,可以改变它
double a[size];
int index=0;
double sum=0;
cout<<"请输入数据,输入任意字母确定结束输入"< while(cin>>a[index++])//输入数组
{
if(index > size -1)
break;
}
cout<<"输入数据为:"< for(int k=0; k cout< cout< for(int i=0; i sum+=a[i];
double eva = sum/(index-1); //求平均值
double s=0;
for(int j=0; j s +=(a[j] - eva)*(a[j]-eva);
double ss = sqrt(s/(index-1)); //求均方差
cout<<"均方差为"< return 0;
}

回答2:

简单点的:

int nLength = 10 ; // length of array
int *pArray = 0 ; // points to an array
pArray = new int[nLength] ; // allocate memory

// step1. read data
int nElement = 0 ;
for(int i = 0 ; i < nLength; i++) // read input data into array
{
cin>>nElement ;
pArray[i] = nElement ;
}

// step2. compute variance
float mean = 0 ;
float variance = 0 ;

// compute mean
for(int i = 0 ; i < nLength; i++)
{
mean += pArray[i] ;
}
mean = mean / nLength ;

// compute variance
float temp = 0 ;
for(int i = 0 ; i < nLength; i++)
{
temp = (pArray[i] - mean) * (pArray[i] - mean) ;
variance += temp ;
}
variance = variance / nLength ;