|
From: Shawn <tre...@gm...> - 2008-03-15 03:01:12
|
I'm having something strange occur. When someone enters a negative
number in my program for either the deposit amount or the withdrawal
amounts, it loops and prompts for the user again...but it also subtracts
the negative number from my running total! Shouldn't the input
validation keep that from happening? Am I missing something? The code
is below with the suspected portions highlighted ...thanks!
int main()
{
//declare and initialize variables
float startBalance = 0;
float withdrawAmount = 0;
float depositAmount = 0;
float totalDeposits = 0;
float totalWithdrawals = 0;
float finalBalance = 0;
float runningBalance = 0;
//intro
cout<<endl;
cout<<"Welcome to the savings account balance calculator!!!"<<endl;
cout<<endl;
//prompt user for starting balance
cout<<"Please enter the starting balance in the savings account: ";
cin>>startBalance;
cout<<endl;
//add startBalance to runningBalance
runningBalance += startBalance;
//loop thru 3 month period
for(int i=1; i<=3; ++i)
{//begin month loop
*//prompt user for deposit amount
do
{//begin do while
cout<<"Please enter month "<<i<<" deposit amount: ";
cin>>depositAmount;
runningBalance += depositAmount;
totalDeposits += depositAmount;
//input validation
if (depositAmount < 0)
cout<<"Please enter a positive number."<<endl;
cout<<endl;
}//end do while
while (depositAmount < 0);*
*do
{//begin do while
//prompt user for withdrawal amount
cout<<"Please enter month "<<i<<" withdrawal amount: ";
cin>>withdrawAmount;
totalWithdrawals += withdrawAmount;
cout<<endl;
//input validation
if (withdrawAmount < 0 || withdrawAmount > runningBalance)
{cout<<"Please enter either a positive number or a number that isn't
greater";
cout<<" then the balance."<<endl;
cout<<endl;}
}//end do while
while (withdrawAmount < 0 || withdrawAmount > runningBalance);
cout<<totalWithdrawals;
}//end month loop*
//calculate the final balance
finalBalance = runningBalance - totalWithdrawals;
cout<<endl;
//display output
cout<<fixed<<showpoint;
cout <<"Starting balance:\t$"<<setprecision(2)<<startBalance<<".\n\n";
cout <<"Total Deposits:\t\t$"<<setprecision(2)<<totalDeposits<<".\n\n";
cout <<"Total Withdrawals:\t$"<<setprecision(2)<<totalWithdrawals<<".\n\n";
cout <<"Final Balance:\t\t$"<<setprecision(2)<<finalBalance<<".\n";
return 0;
}
|