下面是我正在編寫的用於學習如何在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;
}
+1。作爲一個經驗法則,你應該幾乎總是在聲明它們的地方初始化局部變量。 –
在聲明中初始化變量是一個很好的習慣。好答案。 – JoeFish