使用file查找c ++中的标准偏差

时间:2016-07-15 17:48:47

标签: c++

编写一个程序,从一个double类型的文件中获取其输入。程序向屏幕输出文件中数字的标准偏差。该文件只包含由空格和/或换行符分隔的double类型的数字。数字列表x1,x2,x3等的标准偏差定义为平方根:

((x1 - a)2 +(x2 - a)2 +(x3 - a)2 + ...)/(n - 1)

其中数字a是数字x1,x2,x3等的平均值,数字n是数字的数量。

您的程序应将文件名作为用户的输入。

我已在计算机中创建了一个文件。当我完成代码并尝试编译它时,它无法在编译器中打开该文件。我不知道发生了什么问题。谁能给我一些建议?

#include <stdio.h>
#include <iostream>
#include <cmath>
#include <fstream>
#include <string>

using namespace std;


int main()
{
    double next, avg,var,stdDev, sum=0, sumSq=0;
    int count=0;

    cout << "Enter filename:" << endl;
    std::string filename;
    cin >> filename;

    ifstream in_stream;

in_stream.open(filename.c_str());


   while(in_stream >> next)
   {
       sum+=next;
       sumSq+=(next*next);
       ++count;       
   }

   avg=sum/count;
   var=(count*sumSq-sum*sum) / (count*(count-1));
   stdDev=sqrt(var);

   in_stream.close();

cout.setf(ios::showpoint);
cout.setf(ios::fixed);
cout.precision(3);
cout << "The standard deviation is " << stdDev << endl;



return 0;
}



 [1]: http://i.stack.imgur.com/luJZx.png



 [2]: http://i.stack.imgur.com/ofZGR.png


 [3]: http://i.stack.imgur.com/xTFSL.png

1 个答案:

答案 0 :(得分:0)

这就是你需要的

#include <iostream>
#include <cmath>
#include <fstream>
#include <string>

using namespace std;

int main() {
  double next, avg, var, stdDev, sum=0, sumSq=0;
  int count=0;

  cout << "Enter filename: ";
  std::string filename;
  cin >> filename;

  ifstream in_stream;
  in_stream.open(filename.c_str());
  if(in_stream.fail()) {
    cout << "Could not open the file " << endl;
    exit(0);
  }

  while(in_stream >> next) {
    sum += next;
    // sum the square of "next"
    sumSq += (next * next);
    ++count;
  }

  avg = sum/count;
  var = (count*sumSq - sum*sum)/(count*(count - 1));
  stdDev = sqrt(var);

  cout << "The mean is: " << avg << endl;
  cout << "The unbiased sample variance is: " << var << endl;
  cout << "The unbiased sample standard deviation is: " << stdDev << endl;

  return 0;
}

编译并执行 SAME 目录中的可执行文件作为nums.txt文件。然后在程序提示您Enter filename:后,输入nums.txt。例如,终端中我的会话的屏幕抓取是:

enter image description here

我使用了g++,但您也可以使用clang++进行编译。

希望这有帮助。

相关问题