【发布时间】:2016-11-15 00:43:18
【问题描述】:
我成功地循环了一个文件,该文件提供了某天的行驶里程、使用的加仑数和汽油成本。现在我试图弄清楚如何通过使用循环来获得行驶里程、使用加仑和汽油成本的总和
int main()
{
ifstream inputFile;
int x = 1;
int milesDriven = 0;
double gallonsUsed = 0,
gasolineCost = 0;
int truckNumber,
numberOfTrips,
sumMilesDriven = 0;
double sumGallonsUsed = 0,
sumGasolineCost = 0;
int avgMilesDriven;
double avgGallonsUsed,
avgGasolineCost;
/* Display Truck Information
Get Number of Trips
Get Truck Information
Process Each Trip
Display Averages
*/
inputFile.open("100.txt");
//Display Truck Information
cout << " " << setw(35) << "Red-Rig Trucking" << endl << endl;
cout << " " << setw(40) << "Summary of Truck Operations" << endl << endl;
inputFile >> truckNumber;
cout << "Truck: " << truckNumber << endl << endl;
inputFile.close( );
inputFile.open("truck.txt");
//Get Number of Trips
inputFile >> numberOfTrips;
//Get Truck Information
cout << "Day" << " " <<setw(16) << "Miles" << " " << setw(16) << "Gallons"
<< " " << setw(16) << "Gasoline" << endl << setw(20) << "Driven" << " "
<< setw(16) << "Used" << " " << setw(16) << "Cost" << endl << endl;
while(!inputFile.eof()){
inputFile >> milesDriven >> gallonsUsed >> gasolineCost;
cout << x << " " << setw(17) << milesDriven << " " << setw(17)
<< fixed << setprecision(2) << gallonsUsed << " " << setw(12) << fixed
<< setprecision << gasolineCost << endl ;
x++;
}
//Process Each Trip
/*while(inputFile)
{ sumMilesDriven = sumMilesDriven + milesDriven;
inputFile >> milesDriven;
}*/
for (; milesDriven--;)
sumMilesDriven += milesDriven;
cout << endl << "Sum" << " " << setw(15) << sumMilesDriven ;
for (;gallonsUsed;)
sumGallonsUsed += gallonsUsed;
cout << " " << setw(17) << sumGallonsUsed;
for (;gasolineCost--;)
sumGasolineCost += gasolineCost;
inputFile.close( );
return 0;
}
我已经走到了这一步,但我不知道出了什么问题。我已经从 for 循环括号中取出了 milesDriven >=10。当代码运行时,我得到的总金额不正确。总和要么太大要么太小。
【问题讨论】:
-
什么语言? JS? Python?添加标签。
-
sumMilesDriven是否在您的代码中的其他位置声明? -
现在,您正试图将变量添加到
sumMilesDriven中,而该变量实际上并没有以理智的方式发生变化。通常对于这样的分配,您要么从数据“数组”中读取,要么需要从 soemwhere 输入/输入数据,然后在循环中求和。然后,您将需要一种方法来知道何时输入了所有数据,以便知道何时跳出循环。 -
我使用的是 c++,是的 sumMilesDriven 是在代码中声明的。
-
你的代码显然不完整。请粘贴完整的代码。