gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 03:06:47 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com