So I must create a function that uses a static variable to keep track of a bank balance (it should be in a separate function but I can't even get this straightened out). I'm running into some issues and I think I might be using the static variable/function wrong. my overdraft is coming up properly but its factoring in the (-) negative amount when it should just be voiding that entry. Like I said, this should be in the form of two functions and one containing the bank balance, but I seem to have all the lines of code in that void function and my main function is just calling that function.. pretty sure that's not how it should go.
#include <iostream>
#include <iomanip>
usingnamespace std;
int main()
{
cout << fixed << setprecision(2);
char choice;
staticdouble balance;
double cash;
do
{
cout << "Enter amount of transaction, positive for deposit, negative for withdrawal" << endl;
cin >> cash;
balance += cash;
//if statment to prevent an overdraft
if (balance >= 0)
cout << "Current Balance = " << balance << endl;
else
cout << "Impermissible withdrawal, insufficient funds!" << endl;
cout << "Do you have more transactions? <Y or N>"; // runs another transaction when user enters "Y/y"
cin >> choice;
} while (choice == 'Y' || choice == 'y');
cout << "Final Balance " << balance << endl;
return 0;
}
/*
Enter amount of transaction, positive for depostit, negative for withdrawal
50
Current Balance = 50.00
Do you have more transactions? <Y or N>y
Enter amount of transaction, positive for deposit, negative for withdrawal
50
Current Balance = 100.00
Do you have more transactions? <Y or N>y
Enter amount of transaction, positive for deposit, negative for withdrawal
-105
Impermissible withdrawal, insufficient funds!
Do you have more transactions? <Y or N>y
Enter amount of transaction, positive for deposit, negative for withdrawal
50
Current Balance = 45.00
Do you have more transactions? <Y or N>n
Final Balance 45.00
Press any key to continue . . .
*/
int foo()
{
staticint x = 0;
return x++;
}
int main()
{
for(int z = 0; z < 10; z++)
cout << foo() << endl;
}
Run this.
ok, now, what you just saw was that x in foo is keeping its value, even though the function exited. Now remove the static keyword, and you get a totally different behavior: x forgets its value every time it runs and it goes back to zero every time. Static values inside functions exist for the life of the PROGRAM not the life of the function.
Given that, what you are asked to do is write a function that uses this capability to keep track of a value. Can you do it now?