0

皆さん、こんにちは。数字を含む入力ファイルを読み取り、次の方法を使用して標準偏差を求めるプログラムを作成する必要があります。

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

x は読み取った桁数に等しく、mu は平均値に等しくなります。while ループ内で入力ファイルから読み込まれた値に異なる変数 (x1、x2、x3、x4) を設定する方法がわからないため、これを行うのに問題があります。また、最初の桁を読み取り、その後 3 桁ごとに読み取ることになっていることに注意することも重要です。これは私がこれまでに持っているものです:

    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

配列を使用したくない場合は、ファイルを複数回読み取る必要がある場合があります。

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 に答える