我正在研究一个可以计算文件中数字量的程序,并将它们加在一起。
实施例。假设有一个包含数字“1 5 6 2 56 8”的.txt文件。你可以看到有6个数字,总和是78.我自己计算了这些。最后,我希望程序导出另一个文件告诉我“数量:和数字的总和是:”
如何修改程序以使用任何文件执行此操作?
这是我的源代码:
ifstream inFile;
int value1, value2, value3, value4, value5, value6, value7, value8, value9, value10,
value11, value12, value13, value14, value15, value16, value17, value18, value19,
value20;
double average, sum;
//OPEN FILE
inFile.open("data.txt");
//ASSIGN VALUES WITH VARIABLES
inputFile >> value1;
inputFile >> value2;
inputFile >> value3;
inputFile >> value4;
inputFile >> value5;
inputFile >> value6;
inputFile >> value7;
inputFile >> value8;
inputFile >> value9;
inputFile >> value10;
inputFile >> value11;
inputFile >> value12;
inputFile >> value13;
inputFile >> value14;
inputFile >> value15;
inputFile >> value16;
inputFile >> value17;
inputFile >> value18;
inputFile >> value19;
inputFile >> value20;
// CLOSE FILE
input.close();
//CALCULATE THE SUM
sum = value1 + value2 + value3 + value4 + value5 + value6 + value7 + value8 + value9 + value10 +
value11 + value12 + value13 + value14 + value15 + value16 + value17 + value18 + value19 + value20;
//CALCULATE THE AVERGAGE
average = sum / 20;
ofstream outputFile;
outputFile.open("results.txt");
outputFile << "The number of the values is: 20" << endl;
outputFile << "The total is: " << sum << endl;
outputFile << "The average is: " << average << endl;
outputFile.close();
return 0;
}
答案 0 :(得分:3)
您应该了解 for循环和 while循环。在这种情况下, while循环可能最适用:
int main() {
std::ifstream inFile("data.txt");
int value, sum = 0, count = 0;
while(inFile >> value) {
sum += value;
count += 1;
}
assert(count > 0);
std::cout << "sum: " << sum << "\n";
std::cout << "average: " << (double) sum / count << "\n";
}
答案 1 :(得分:0)