如何使用循环函数找到总和?

时间:2016-11-15 00:43:18

标签: c++ loops for-loop sum

我能够成功循环一个文件,该文件给我带来行驶里程,加仑使用和汽油成本。现在,我试图通过使用循环来弄清楚如何获得行驶里程,使用加仑和汽油成本的总和

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。当代码运行时,我收到的金额不正确。总和太大或太小。

1 个答案:

答案 0 :(得分:0)

您的代码:

for (sumGasolineCost += gasolineCost; gasolineCost >= 1; gasolineCost--);{ 
 cout << " " << setw(17) << sumGasolineCost;
} 

我的第一个建议是,不要写令人困惑的代码。无论何时进行编程,您都可以做好比将鞋带绑在一起更好的事情。我想你知道上面的内容相当于:

for (sumGasolineCost += gasolineCost; gasolineCost >= 1; gasolineCost--);

cout << " " << setw(17) << sumGasolineCost;

这让我们讨论循环本身。回去查阅你的教科书。 for循环有三个组成部分:

for( init ; test ; incr )
  • init 执行一次,通常用于初始化将要测试的内容
  • test 在每次迭代时执行,包括第一次,以确定是否将执行循环体
  • incr 在循环体后执行,通常用于更新测试值

在您的情况下,sumGasolineCost += gasolineCost位于init。它被执行一次。它应该在循环体中。还有其他错误。我不能更具体,因为你没有指出数组或输入是你在哪里循环。

一旦你的循环完成它应该做的事情,你可能会发现标准的std :: accumulate函数比较有趣。