0

大家好,我需要创建一个程序,该程序读取包含数字的输入文件,然后使用以下方法找到标准偏差:

sqrt(( x1 - mu )^2 + ( x2 - mu )^2 + ( x3 - mu )^2 + ( x4 - mu )^2)/mu

x 等于读入的数字,mu 等于平均值​​。我在执行此操作时遇到了麻烦,因为我不知道如何为在我的 while 循环中从输入文件中读取的值设置不同的变量(x1、x2、x3、x4)。同样重要的是要注意,我们应该读取第一个数字,然后每隔三个数字读取一次。这是我到目前为止所拥有的:

    fin.open(FileName.c_str());
    if (fin.fail())
    {
        cout <<"Bad file name or location.\n" ;
        exit(0);
    }
    fin >> X;
    first_score = X;
    Counter = 0, Sum=0;
    while (!fin.eof() )
    {   
        Counter++;
        if (Counter%3==0)
        {
            fin >> X;
            Sum += X;
            Counter++;
            Counter2 ++ ;
            Avg = (Sum+first_score)/(Counter2+1);
            deviation = pow((X-Avg),2);
            sum_of_deviations += deviation;
        }
        fin >> Score;
    }
    quotient_of_deviations = sum_of_deviations/Counter2;
    standard_dev2 = sqrt(quotient_of_deviations);
    fin.close();

我知道这段代码在逻辑上是不正确的,因为我从每个 x 值中减去了不同的平均值。有人知道每次运行 while 循环时如何将 while 循环中的 X 分配给一个新变量吗?如果我能做到这一点,我就可以在循环外用相同的平均值减去每个 x 值。我希望我解释得足够好,以便你们能够理解我的问题。如果没有,我会很乐意解释更多。在此先感谢您的时间。

4

2 回答 2

1

这样做的问题是您需要知道平均值的值,但是在您读入所有数据之前您不会知道这一点。您正在尝试根据迄今为止读取的术语的平均值来计算偏差。这是不正确的

您应该使用 sqrt(Sum(x^2) /n - (sum(n) /n)^2) 公式计算标准差。

计算循环中的两个和,然后除以n,最后完成计算。然后你不需要每次都分配一个新变量。

于 2013-10-20T01:26:50.437 回答
1

如果您不想使用数组,那么您可能需要多次读取文件。

int counter = 0;
int sum1=0;
ifstream fin,fin2;   //fin and fin2 to read the file each time.
fin.open("myfile.txt");  //opening a file to read it.



while (!fin.eof() )   //reading a file
{
   fin>>X;
   sum1  = sum1+X;    //adding all the numbers in the file
   counter++;      //counting number of items in the file

}

fin.close()
//Now first calculate mean
int mean=0;
mean = sum1/counter;   //calculating the mean

//now calculate sum of squares of difference of each term and mean
int sum2=0;
fin2.open("myfile.txt");     //again opening the file with fin2

while (!fin2.eof() )   //again reading the file
{
   fin2>>Y;
   sum2  = sum2+ pow(Y-mean,2);     

}

fin2.close()


 //finally standard deviation

 double sd=0;

 sd = sqrt(sum2/mean);    //calculating standard deviation
于 2013-10-20T01:39:14.107 回答