【发布时间】:2023-03-18 09:53:01
【问题描述】:
我想从 .dat 文件中读取数字,然后计算标准偏差并输出文件中数字的数量。我相信我的均值和标准差函数是正确的。真正让我失望的是从文件中将数字输入到函数中。这是我目前所拥有的。
#include "pch.h"
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <cmath>
using namespace std;
const int MAX_COUNT = 1000; //for max size of array
double Mean(double*, int); //calculates average of numbers
double Standard_Deviation(double*, int); //calculates standard deviation
void Magic_Number();
ifstream InFile;
int main()
{
Homework_Header();
string NameOfInputFile = "StdDev.dat";
InFile.open("StdDev.dat");
if (InFile.fail()) {
cout << "Cannot open file: " << NameOfInputFile << "\d";
exit(1);
}
int SamplePoint = 0;
double dataPoint[MAX_COUNT];
double sd = Standard_Deviation(dataPoint, MAX_COUNT);
while (InFile >> dataPoint)
{
void Magic_Number();
sd = Standard_Deviation(dataPoint, MAX_COUNT);
SamplePoint++;
if (InFile.eof())break;
}
cout << "The Standard Deviation is: " << sd << endl;
cout <<SamplePoint << " records process \n";
InFile.close();
if (InFile.fail()) {
cout << "Cannot close file: " << NameOfInputFile << "\d";
exit(-5);
}
cin.get();
return 0;
}
void Magic_Number()
{
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
}
double Mean(double* numbers, int count)
{
double calculated_mean = 0.0;
for (int i = 0; i < count; ++i)
{
calculated_mean += numbers[i];
}
calculated_mean /= double(count);
return calculated_mean;
}
double Standard_Deviation(double* numbers, int count) // * is pointer: special variable that has a memory address as value
{
double std_dev = 0.0;
double average = Mean(numbers, count); //Mean of numbers
double temp_dev;
for (int i = 0; i < count; ++i)
{
temp_dev = numbers[i] - average; //sets temp_dev to be the deviation from the average
std_dev += temp_dev * temp_dev; //adds squares of the deviations
}
std_dev /= double(count);
std_dev = sqrt(std_dev); // square roots
return std_dev;
}
【问题讨论】:
-
您的问题是什么?如果您遇到编译器错误,请告诉我们它们是什么以及您希望产生错误的代码在哪里以及做什么。我遇到了很多错误。
-
具体错误在这一行: while (InFile >> dataPoint) 。我想说我的文件正在输入数据点。没有“>>”运算符与这些操作数匹配。
-
dataPoint是一个双精度数组。您一次只能读取一个 double,因此您需要索引到要写入的数组元素。 -
所以:对于 (int i = 0; i
-
要么使用您现在拥有的
while循环,要么将其替换为循环,无论哪种情况,请确保在>>操作失败时离开它。顺便说一句,您已经有一个柜台:SamplePoint。此外,您每次在循环内计算标准偏差对我来说毫无意义。