大家好我需要创建一个程序来读入包含数字的输入文件,然后使用以下方法找到标准偏差:
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值。我希望我解释得那么好,以便你们能理解我的问题。如果不是,我会很乐意解释更多。提前感谢您的时间。
答案 0 :(得分:1)
这个问题是你需要知道平均值,但在读完所有数据之前你不会知道。您正尝试根据到目前为止读取的术语的平均值来计算偏差。这是不正确的
您应该使用sqrt(Sum(x ^ 2)/ n - (sum(n)/ n)^ 2)公式作为标准偏差。
计算循环中的两个和,然后除以n并在结束时完成计算。那么您不需要每次都分配一个新变量。
答案 1 :(得分: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