C++ 是否使用未初始化的局部变量?
课堂练习有问题吗C++ 是否使用未初始化的局部变量?,c++,validation,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-whil
#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;
}
#包括
#包括
使用名称空间std;
int main()
{
国际雇员号、格罗斯佩、州税、联邦税、菲卡霍尔德;
int totalGross、totalState、totalFederal、totalFica、totalPay=0;
do//do while循环查找员工编号
{
国家税收;
}而(州税<0 | |州税>grossPay);
do//entry and validation联邦税
{
联邦税;
}而(联邦税<0 | |联邦税>grossPay);
do//FICA控股金额的输入和验证
{
库特>菲卡霍尔德;
}而(ficaHold<0 | | ficaHold>grossPay);
if(grossPay cout第一次使用totalState
时,您正在读写:totalState+=stateTax;
。问题是您从未初始化过totalState
,因此无法保证在尝试读取它时值会是多少
作为记录,您有:totalGross
、totalFederal
和totalFica
“我已经在任何循环之前的声明中给出了这些变量的值”没有。只有totalPay
是用0
初始化的。非常感谢@songyuanyao,我以为如果用逗号分隔,你可以列出所有变量,将它们初始化为相同的数字,但我搞错了。像这样初始化多个变量的正确方法是什么,或者是列出“int a=0;int b=0;…等”是唯一的方法?或者int a=0,b=0,…;
。在我看来,最好每行定义一个变量。