c++ - 使用 While 循环的标准偏差程序 cpp/c++

标签 c++ loops standards deviation

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

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 值。我希望我解释得足够好,以便你们能够理解我的问题。如果没有,我会很乐意解释更多。提前感谢您的宝贵时间。

最佳答案

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

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

关于c++ - 使用 While 循环的标准偏差程序 cpp/c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19472849/

相关文章:

c++ - curl_easy_perform 返回 CURLE_WRITE_ERROR,但我不会写任何东西

c++ - QWebEngineView 立即崩溃,尤其是在滚动后 - Qt5.8

java - 为什么 while 循环后没有打印任何内容?

matlab - 如何模拟电影?

c++ - 内存占用增加

c++ - C++ 中的密码 |打印后删除字符

windows - 批处理文件编程中使用 'for'循环显示前N个自然数

sql - 在 SQL Server 中使用 ODBC 日期字符串文字有任何性能缺点吗?它比常规字符串日期文字更好吗?

c++ - 在 C++11 标准中哪里说 char* p = "abc";是病态的?

c - UINT_MAX + 1 等于什么?