使用未初始化的局部变量?

时间:2018-04-04 01:54:28

标签: c++ validation

课堂练习有些问题

#include <iostream>
#include <string>
using namespace std;

int main()
{
    int employeeNumber, grossPay, stateTax, federalTax, ficaHold;
    int totalGross, totalState, totalFederal, totalFica, totalPay = 0;


    do // do-while loop for employee number
    {
        cout << "Enter the employee number: " << endl;
        cout << "(Enter 0 to quit.)" << endl;
        cin >> employeeNumber;

    } while (employeeNumber < 0);

    while (employeeNumber != 0)
    {
        do // gross pay greater than state tax + federal tax + FICA
        {
            do // entry and validation for gross pay
            {
                cout << "How much gross pay ? ";
                cin >> grossPay;
            } while (grossPay < 0);


            do //entry and validation for state tax
            {
                cout << "How much state tax ? ";
                cin >> stateTax;
            } while (stateTax < 0 || stateTax > grossPay);


            do // entry and validation federal tax
            {
                cout << "How much federal tax ? ";
                cin >> federalTax;
            } while (federalTax < 0 || federalTax > grossPay);


            do // entry and validation for FICA holdings amount
            {
                cout << "How much FICA withholdings ? ";
                cin >> ficaHold;
            } while (ficaHold < 0 || ficaHold > grossPay);


            if (grossPay < stateTax + federalTax + ficaHold) // Message to verify taxes are not greater than pay
                cout << "State tax, federal tax, and FICA holdings cannot be greater than gross pay. Please re-enter these values." << endl;


        } while (grossPay < stateTax + federalTax + ficaHold);


        totalGross += grossPay;
        totalState += stateTax;
        totalFederal += federalTax;
        totalFica += ficaHold;
        totalPay = totalGross - (totalState + totalFederal + totalFica);

        do // do-while loop for employee number
        {
            cout << "Enter the employee number: " << endl;
            cout << "(Enter 0 to quit.)" << endl;
            cin >> employeeNumber;
        } while (employeeNumber < 0);

    }

    cout << endl << endl << "The total gross pay is: $" << totalGross << endl;
    cout << "The total state tax is :" << totalState << endl;
    cout << "The total federal tax :" << totalFederal << endl;
    cout << "The total FICA withholdings :" << totalFica << endl;
    cout << "Net pay :" << totalPay << endl << endl;
    return 0;
}

在第95-98行的变量上得到一些错误,例如“未初始化的局部变量'totalState'”并且不确定该做什么,我已经在任何循环之前在声明中给出了这些变量值,我不确定是否在保持计划目标的同时,我可以在任何事情之前移动它们

1 个答案:

答案 0 :(得分:1)

首次使用totalState时,您既可以阅读又可以写作:totalState += stateTax;。问题是您从未初始化totalState,因此当您尝试阅读时,我们无法保证其价值。

要进行记录,您有other uninitialized variables as welltotalGrosstotalFederaltotalFica