从文件 C++ 中查找标准偏差

时间:2021-07-07 13:25:11

标签: c++ standard-deviation

我进行了编码以找到与提供的文件的标准偏差。我的讲师建议在功能上这样做。这是我尝试过的编码。但是在主函数中调用函数有错误。它说 std 不能隐蔽地浮动。我应该怎么做才能找到文件中的标准偏差?

#include <iostream>
#include <cmath>
#include <fstream>
#include <string>
using namespace std;

float calculateSD(float namefile);

int main()
{
   string input;  
   ifstream namefile("payment.txt"); 

   if (!namefile)
       return (cout << " ERROR : cannot open file.\n"), 1; 

   while (getline(namefile, input)) 
        cout << input << endl;

   namefile.clear();   
   namefile.seekg(0);  

   int a {}, b {}, c {};
   nameFile >> a >> b >> c ;

   calculateSD(nameFile >> a >> b >> c);
}

float calculateSD(float nameFile)
{
   float sum1 = 0.0, sum2 = 0.0, sum3 = 0.0;
   float mean1, mean2, mean3;
   float standardDeviation1 = 0.0, standardDeviation2 = 0.0, standardDeviation3 = 0.0;

    for (int a {}, b {}, c {}; namefile >> a >> b >> c; )
  {
    sum1 += a;
    sum2 += b;
    sum3 += c;
  }

    mean1 = sum1/10;
    mean2 = sum2/10;
    mean3 = sum3/10;

   for (int a {}, b {}, c {}; nameFile >> a >> b >> c ; )
  {
        standardDeviation1 += pow(a - mean1, 2);
        standardDeviation2 += pow(b - mean2, 2);
        standardDeviation3 += pow(c - mean3, 2);
  }

 cout << "Standard Deviation 1  = " << sqrt(standardDeviation1 / 10) << endl;
 cout << "Standard Deviation 2 = " << sqrt(standardDeviation2 / 10)<< endl;
 cout << "Standard Deviation 3 = " << sqrt(standardDeviation3 / 10)<< endl;

return 0;
}

如果你们能帮助我真的很感激

2 个答案:

答案 0 :(得分:0)

你做错了很多。首先关闭您的功能

float calculateSD(float nameFile);

出于某种原因接受 float nameFile,但您可能指的是 ifstream& nameFile(尽管您命名此变量的方式仍然令人困惑)。

之后在 main() 中,您尝试像这样调用此函数

int a {}, b {}, c {};
nameFile >> a >> b >> c ;

calculateSD(nameFile >> a >> b >> c);

为什么在开始计算标准偏差之前要从文件中读取 6 个数字?现在您的结果可能不正确。更不用说你打错了——你把你的流定义为 ifstream namefile("payment.txt");,注意它叫做 namefile,没有大写 F,但后来你尝试将它用作 {{1} } 变量,它不存在。您可能打算像这样传递它:

nameFile

答案 1 :(得分:0)

您正在尝试拆分功能,这很好。问题是您在掌握应该传递给函数的内容方面存在问题。

试试这个方法:

std::vector<double> loadValues(std::istream& f) {
     double x;
     std::vector<double> v;
     while(f >> x) v.push_back(x);
     return v;
}

double standardDeviationFrom(const std::vector<double>& v)
{
     ... // do it yourself
}

double standardDeviationFrom(std::istream& f)
{
    return standardDeviationFrom(loadValues(f))
}

double standardDeviationFrom(std::filesystem::path p)
{
    std::ifstream f{p};
    if (!f) {
        std::perror("standardDeviationFrom");
        return std::nan("1");
    }
    return standardDeviationFrom(f);
}
相关问题