下面是我正在编写的代码,用于学习如何在 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;
}
最佳答案
您没有首先初始化您的变量,因此它们没有任何初始值。然后你向这些变量添加一些东西,结果是未定义的(读取垃圾)。
考虑像这样声明它们:
double beginningTotal = 0, purchaseTotal = 0, paymentsTotal = 0, financeChargeTotal = 0, endingTotal = 0;
...甚至更好 - 为它们创建一些结构。
关于c++ - 初始化变量时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7895186/