下面是我正在编写的代码,用于了解如何在C ++中使用文件。我有正确读取和写入的所有内容,但我无法让我的显示器显示正确的值,因为当我尝试初始化while循环中的Total变量时它忽略了。
#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;
}
答案 0 :(得分:5)
您没有首先初始化变量,因此它们没有任何初始值。然后你向这些变量添加一些东西,结果是未定义的(读取垃圾)。
考虑将它们声明为:
double beginningTotal = 0, purchaseTotal = 0, paymentsTotal = 0, financeChargeTotal = 0, endingTotal = 0;
......甚至更好 - 为他们创造一些结构。
答案 1 :(得分:2)
beginningTotal += beginningBalance
与
意思相同beginningTotal = beginningTotal + beginningBalance
在循环之前没有初始化beginTotal,所以第一次得到
beginningTotal = _indeterminant_value_ + beginningBalance
因此,BeginTotal始终是一个不确定的值。通过不使用未初始化的变量来修复它。
double beginningTotal = 0.0;