【发布时间】:2016-01-20 14:32:53
【问题描述】:
我昨晚在此发布了一些内容,但我决定稍微改变我的方法,因为我没有完全理解我试图使用的代码。
我很抱歉,因为我知道这个话题已经被写死了,但我希望对我编写的代码有所帮助。
我正在从我的计算机中加载一个 .txt 文件,其中包含 100 个整数。它们都在新行中。
这是我目前的代码:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main ()
{
ifstream fout;
ifstream fin;
string line;
ifstream myfile ("100intergers.txt");
if (myfile.is_open())
{
while ( getline(myfile,line) )
{
cout << line << '\n';
}
// Closes my file
myfile.close();
// If my file is still open, then show closing error
if (myfile.is_open())
cerr << "Error closing file" << endl;
exit(1);
}
int y = 0;
int z = 0;
int sum = 0;
double avg = 0.0;
avg = sum/(y+z);
cout << endl << endl;
cout << "sum = " << sum << endl;
cout << "average = " << avg << endl;
// checking for error
if (!myfile.eof())
{
cerr << "Error reading file" << endl;
exit(2);
}
// close file stream "myfile"
myfile.close();
return(0);
}
当我运行它时,我得到退出代码 1(以及我的 100 个整数的列表)。
这意味着我的 if 子句不是正确的选择,还有什么更好的选择?
如果我完全删除该位,它无法运行我认为是 0/0*0 的算术错误
此外,我认为我为 .txt 文件编写的代码是针对单词而非数字的,但是当我将 string 更改为 int 时,它确实会出错并告诉我我遇到的问题比没有的要多。
最后 - 在此之后我想创建一个数组来计算方差 - 有什么提示吗?
干杯
杰克
【问题讨论】:
-
您是否要对文件中的整数进行实际求和?照原样,你只是除以零......
-
要计算方差,只需要存储
n^2的总和即可。无需存储所有内容。 -
在 .txt 文件中?不,这只是一个列表,例如:1 2 等
标签: c++ arrays sum average mean