我是编码的新手。我得到了这项任务,我几乎已经完成但仍坚持到最后一步。我老师给了我们正整数文件。任务是找到一行的每行和总输出的总和,以及文件中所有数字的总和。我的线路总工作正常,但当我尝试总共所有数字时,我得到了错误的答案。
请查看我的代码并告诉我我做错了什么。
以下是代码:
#include <iostream>
#include <string>
#include <fstream>
#include<iomanip>
using namespace std;
int main()
{
ifstream infile; ofstream outfile;
int counter, counter2, line, sum, num;
double total;
infile.open("E:\\Lab assignments\\numberfile.txt");
if (!infile)
{
cout << "File not found, closing program" << endl;
system("pause");
exit(1);
}
outfile.open("E:\\Lab assignments\\outfile.txt");
if (!outfile)
{
cout << "Output file could not be created, closing program" << endl;
system("pause");
exit(1);
}
while (!infile.eof())
for (counter = 1; counter <= 8; counter++)
{
sum = 0;
if (counter != 9)
{
for (line = 1; line < 8; line++)
{
infile >> num;
outfile << right;
outfile << setw(6);
outfile << num << " ";
sum = sum + num;
outfile << " ";
}
outfile << "Total per line = " << sum;
outfile << endl;
}
}
total = 0;
for (counter2 = 0; counter2 <= 8; counter2++)
{
{
infile >> sum;
total = total + sum;
}
}
outfile << "All numbers total= " << total;
infile.close();
outfile.close();
return 0;
}
并带有数字的文件:
346 130 982 90 656 117 595 415 948 126 4 558 571 87 42 360 412 721 463 47 119 441 190 985 214 509 2 571 77 81 681 651 995 93 74 310 9 995 561 92 14 288 466 664 892 8 766 34 639 151 64 98 813 67 834 369
答案 0 :(得分:1)
计算同一循环中每一行的总和和总和将大大简化您的任务,它将消除代码中的隐藏问题。简单:)