c++ - 初始化变量时遇到问题

标签 c++

下面是我正在编写的代码,用于学习如何在 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/

相关文章:

c++ - 减少持久数据结构中的shared_ptr数量

c++ - 使用 float 的系列总和

c++ - 错误 : invalid suffix "b11111111111111111111111111111111" on integer constant

C++:在堆分配之前使用 typeid

iphone - CoreGraphics 替代品?

python - pybind11::dict 中的 pybind11::对象

c++ - 将枚举作为参数传递

c++ - 让我的过程保持活力 - 永远

C++模板运算符编译错误

c++ - 不完整类型的调用运算符的 decltype 的特殊行为