2011-10-25 146 views
0

下面是我正在編寫的用於學習如何在C++中使用文件的代碼。我有一切正確的閱讀和寫作,但我無法讓我的顯示器顯示正確的值,因爲它忽略了當我嘗試在while循環中初始化總變量。無法初始化變量

#include <iostream> 
#include <iomanip> 
#include <fstream> 
using namespace std; 

int main() 
{ 
    int customerNumber; 
    double beginningBalance, purchase, payments, financeCharge, endingBalance; 
    double beginningTotal, purchaseTotal, paymentsTotal, financeChargeTotal, endingTotal; 
    ifstream inputFile; 
    ofstream outputFile; 

    inputFile.open("BeginningBalance.dat"); 
    outputFile.open("EndingBalance.dat"); 
    cout<<"Cust No | Beginning Bal | Finance Charge | Purchases | Payments | Ending Balance"<<endl; 

    while (inputFile >> customerNumber) 
    { 
     outputFile <<customerNumber<<endl; 
     inputFile >> beginningBalance; 
     inputFile >> purchase; 
     inputFile >> payments; 

     financeCharge = beginningBalance * .01; 
     endingBlanance= beginningBalance + purchase + financeCharge - payments; 

     //*********************************************** 
     //This is where I am having trouble initializing variables. 
     //*********************************************** 
     beginningTotal += beginningBalance; //beginningTotal not being intitialized. 
     financeChargeTotal += financeCharge; 
     purchaseTotal += purchase; 
     paymentsTotal += payments; 
     endingTotal += endingBalance; 

     outputFile <<fixed<<setprecision(2)<<endingBalance<<endl; 

     cout<<setw(5)<<customerNumber<<fixed<<setprecision(2)<<"  "<<beginningBalance<<"  "<<financeCharge<<"   "<<purchase<<"  "<<payments<<"  "<<endingBalance<<endl; 
    } 
    cout<<"Total: "<<fixed<<setprecesion(2)<<beginningTotal<<" "<<financeChargeTotal; 
    system ("PAUSE"); 
    return 0; 
} 

回答

5

您沒有首先初始化變量,所以它們沒有任何初始值。然後你給這些變量添加一些東西,結果是未定義的(閱讀垃圾)。

考慮宣佈他們是這樣的:

double beginningTotal = 0, purchaseTotal = 0, paymentsTotal = 0, financeChargeTotal = 0, endingTotal = 0; 

...甚至更好 - 爲他們創造一些結構。

+3

+1。作爲一個經驗法則,你應該幾乎總是在聲明它們的地方初始化局部變量。 –

+1

在聲明中初始化變量是一個很好的習慣。好答案。 – JoeFish

2
beginningTotal += beginningBalance 

意味着同樣的事情

beginningTotal = beginningTotal + beginningBalance 

beginningTotal循環之前沒有初始化,那麼你身邊的第一時間內得到

beginningTotal = _indeterminant_value_ + beginningBalance 

所以beginningTotal始終是一個超靜定值。通過不使用未初始化的變量來修復它。

double beginningTotal = 0.0;