C++ basic menu driven program (calling functions) - c++

I'm new to programming and am trying to figure out why this is happening.
Basically I'm asked to design a menu driven program that does some basic deposit/withdrawal calculations. I'm supposed to write different functions for each process and call on them when necessary.
I'm having 2 problems:
1) My functions aren't updating my variables within the program. For example it will run, I can enter my starting balance, I can enter my transaction type and amount but every time I switch from deposit to writing a check, it resets the balance to the original user input.
2) When I want the program to exit, it is still asking me for the double input. Not sure how to make it accept just an "E" instead of "E number"
Thanks in advance.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
//Prototypes for my functions that will be called in
void displayMenu();
double checkProcess(double, double);
double depositProcess(double, double);
double totalServCharge(double);
int main()
{
//Variables needed for the problem
char choice; //menu choice
double transAmt, balance, numbServCharge; //transaction amount, current balance, total service charges, number of service charges
numbServCharge = 0; //Start the counter for number of service charges at zero
cout << "Checkbook Program\n\n";
cout << "Enter the beginning balance: ";
cin >> balance; //get the initial balance
cout << endl;
do
{
//Call the display menu function
displayMenu();
//Get user's choice and transaction amount from menu
cout << "Enter a transaction: ";
cin >> choice >> transAmt;
choice = toupper(choice);
cout << endl;
//Create an error message for invalid choice and get a second choice
while((choice != 'C') && (choice != 'D') && (choice != 'E'))
{
cout << "Invalid selection. Please choose C, D or E: ";
cin >> choice;
}
//Set up for option #1 -- using a check
if(choice=='C')
{
//Call check function and service charges function
checkProcess(transAmt, balance);
totalServCharge(numbServCharge);
}
//Set up for option #2 -- deposits
if(choice=='D')
{
//Call deposit function and service charges function
depositProcess(transAmt, balance);
totalServCharge(numbServCharge);
}
}while(choice != 'E'); //Close program if option 3 is selected
//Display final balance
cout << "Processing end of the month";
cout << "\nFinal balance : $ " << fixed << setprecision(2) << balance << endl << endl;
system("pause"); //Pause screen so it doesn't close right away
return 0;
}
void displayMenu()
{
//Highlight menu options
cout << "\nCommands\n";
cout << "C amount - process a check in a specific amount\n";
cout << "D amount - process a deposit in a specific amount\n";
cout << "E - end the program\n\n";
}
double checkProcess(double transAmt, double balance)
{
cout << "\nProcessing check for $" << fixed << setprecision(2) << transAmt;
transAmt = transAmt + .25; //Add the service charge onto the transaction
balance = balance - transAmt; //Update account balence
cout << "\nBalance: $" << fixed << setprecision(2) << balance;
cout << "\nService charge: $0.25 for a check\n";
return balance;
}
double depositProcess(double transAmt, double balance)
{
cout << "\nProcessing Deposit for $" << fixed << setprecision(2) << transAmt << endl;
transAmt = transAmt - 0.25; //Add the service charge onto the deposit
balance = balance + transAmt; //Update account balence
cout << "Balance: $" << fixed << setprecision(2) << balance << endl;
return balance;
}
double totalServCharge(double numbServCharge)
{
double totalServCharge = 0;
numbServCharge++; //Add one to the number of service charges there have been
totalServCharge = .25 * numbServCharge; //Update total cost of service charges
cout << "Total service charges: $" << fixed << setprecision(2) << totalServCharge << endl; //Tell user total service charges so far
return numbServCharge;
}

(1) Your variables aren't updating because you aren't changing them; you're changing the copies passed to your subroutines. You either need to pass the current balance by reference (so that when you change it in the subroutine scope, you're also changing the original) or assign the return value from your subroutines to your current balance.
When you pass a variable by value (as you are now), the program makes a copy of that variable for use in the function scope. When you leave that scope, the copy is deleted. Do this when you want to be sure a subroutine won't alter anything in the scope from which it is called. If you want the subroutine to alter the variables you pass to it, pass the variables by reference. In this function signature, "transAmt" is passed by value and "balance" is passed by reference:
double foo(double transAmt, double& balance);
Incidentally, if you pass the balance by reference there's no reason to return it. You aren't doing anything with the returned value right now anyway.
(2) If you want to not ask for a number when "E" is given, make separate "cin" statements for the number in the conditional blocks for "C" and "D". Right now all your input code is shared between all cases. It would be even better if you arrange things so that you exit the loop before a number is asked for. This way, you only have to write that "cin" statement once.

It's becouse in C++ when you call a function with parameter, you only operate on COPIES of those parameters. If you want to change the original value, pass variable as reference.
See those simple examples:
#include <iostream>
using namespace std;
void normal(int a)
{
a += 10;
}
void by_reference(int &a) //Notice ampersand
{
a += 10;
}
int by_return(int a)
{
return a + 10;
}
int main()
{
int a = 5;
cout << "Start: " << a <<endl;
normal(a);
cout << "Normal: " << a <<endl;
by_reference(a);
cout << "Reference: " << a <<endl;
a = by_return(a);
cout << "Return: " << a <<endl;
}
Now you can see that if you pass the variable as reference it gets changed.
Even if just putting the & before parameter names would fix your problem, I'd recommend you using a return, it generally is simplier and makes your code look better (it's much easier to understand).
Also, correct your indentation. It's very bery important when you work with bigger projects.
Hope this helps. :)

1 | The first problem is occurring because you are not actually modifying the user's input. You are passing the variable in but once the new value is returned you are not storing it, thus the value is forgotten in the main function. Not the best solution, but it might suit you to do this:
if (choice == 'D')
{
//Call deposit function and service charges function
balance = depositProcess(transAmt, balance); // Overwrite balance
numbServCharge = totalServCharge(numbServCharge); // Overwrite numbServCharge
}
Or in a more efficient way, you can pass in the variable by reference. All you would need to do is change the function prototype.
void totalServCharge(double&);
void depositProcess(double&, double&);
Now when the variable is passed in, it will be modified directly by the function. Also note the function data type changed to void because you no longer need to return a value from the function.
2 | Your second problem is the way you handle user input. If you want to ask for multiple input, it might sometimes be best to do it with separate cout and cin statements.
The way it is set in your program is for the user to enter two inputs at once, therefore if you only enter E, it waits patiently as it should for your next input (transAmt). It might be better to process the action desired and then have an amount entered afterwards.
Very general example:
do {
cout << "1 : Transaction or 2 : Exit" << endl;
cin >> choice;
if (choice == 2)
break;
cout << "1. Deposit\n" << "2. Check" << endl;
cout << "Enter transaction type followed by amount" << endl;
cin >> transType >> amount;
// Then do what was specified in choice
} while (true); // Or whatever condition pleases you

Related

Restaurant Billing Program Function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I need to make a restaurant bill calculator program that allows people to choose from a list of menu items (a function) until they have everything they've wanted to order and then calculate the total when they are finished selecting from a list. Then it takes the amount they tender and subtracts the total plus tax and tip to calculate change.
I've found several ideas and similar programs here and on other places but nothing that has given me a good enough idea of how to get this finalized. I have the program coded but I can't figure out how to take the running total and keep accumulating it until the user enters "8". I have a functioning program but it totals after each selection instead of keeping a running total and calcuating it when the user hits the "8" key to end.
Take a look below and see if you can point my in the right direction if you would. Basically this assignment is about functions so we're asked to use functions to display the menu and calculate the total.
#include <iostream>
#include <iomanip>
using namespace std;
// Function Prototypes
void showMenu();
void showFees(double, int);
int main()
{
int choice; //To Hold Menu Choice
double quantity = 1;
//contants for menu choices
const int hamburgerChoice = 1;
const int hotdogChoice = 2;
const int peanutsChoice = 3;
const int popcornChoice = 4;
const int sodaChoice = 5;
const int chipsChoice = 6;
const int waterChoice = 7;
const int endOrderChoice = 8;
//constants for menu prices
const double hamburger = 6.00;
const double hotdog = 4.50;
const double peanuts = 3.75;
const double popcorn = 5.50;
const double soda = 2.80;
const double chips = 1.00;
const double water = 2.00;
//set precision
cout << fixed << showpoint << setprecision(2);
do
{
//display menu and get user choice
showMenu();
cin >> choice;
//validate choice
while (choice < hamburgerChoice || choice > endOrderChoice)
{
cout << "Please enter a valid menu choice: ";
cin >> choice;
}
//if the user does not want to quit proceed
if (choice != endOrderChoice)
{
//display fees
switch (choice)
{
case hamburgerChoice:
showFees(hamburger, quantity);
break;
case hotdogChoice:
showFees(hotdog, quantity);
break;
case peanutsChoice:
showFees(peanuts, quantity);
break;
case popcornChoice:
showFees(popcorn, quantity);
break;
case sodaChoice:
showFees(soda, quantity);
break;
case chipsChoice:
showFees(chips, quantity);
break;
case waterChoice:
showFees(water, quantity);
break;
}
}
}
while (choice != endOrderChoice);
system("pause");
return 0;
}
//*************************************************************
//Definition of function showMenu which displays the menu **
//*************************************************************
void showMenu()
{
cout << "\n\t\tBaseball Game Snacks" << endl;
cout << "1. Hamburger \t$6.00"<< endl;
cout << "2. Hotdog \t\t$4.50" << endl;
cout << "3. Peanuts \t\t$3.75" << endl;
cout << "4. Popcorn \t\t$5.50" << endl;
cout << "5. Soda \t\t$2.80" << endl;
cout << "6. Chips \t\t$1.00"<< endl;
cout << "7. Water \t\t$2.00" << endl;
cout << "8. END ORDER" << endl;
cout << "Please enter your menu choice: ";
}
//************************************************************
//Definition of function showFees which caculates the total **
//bill **
//************************************************************
void showFees(double itemCost, int quantity)
{
double amtTendered;
double totalBill = (itemCost * quantity);
double taxRate = .065;
double tipRate = .20;
double tip = (totalBill * tipRate);
double tax = (totalBill * taxRate);
double amountDue = (totalBill + tax + tip);
cout << "Total Bill: $" << totalBill << endl;
cout << "Tax: $" << tax << endl;
cout << "Tip: $" << tip << endl;
cout << "Total Amount Due: $" << amountDue << endl;
cout << "Enter ammount tendered: $";
cin >> amtTendered;
double changeDue = amtTendered - amountDue;
cout << "Change Due: $" << changeDue << endl;
}
The "balance" is calculated by the showFees function. So, your problem is that you need to maintain the state (some data) in showFees in subsequent calls. The best way you could do this is using OOP. While you are programming in C++ using the procedural paradigm, I will point you some of the solutions available in procedural programming.
Global variables
You could have a global variable to hold the total. This is the simplest, the most intuitive and the worst solution you could have. Don't.
Static variables
You could have a static variable in showFees that stores the current total. Better than a global variable, but still bad.
Store the total in main
Create a variable that represents the total, initialize it to 0 and create a third argument of showFees that takes a pointer to a double. This way, the changes done to that variable will remain after the showFees function call ends. In C++ you can use references also (this is the recommended way in C++).
Improve your program
In programming there is a concept called modularity. Using functions, you don't have duplicate code. But a function should do only one thing, and do it as best as possible. This way, your functions are smaller and easier to manage. In showFees you do 2 things: compute some financial things and generate output. This should always be separated. The computations, or business logic, should be done in a function (that can work in the way I described above), and the output generation, or visual logic, in another function.
Of course, this is a small program and the separation that I talk about is probably an overkill. However, you can think at ways to improve your function so that they are as modular as possible.

Simple bank account program does not store the balance correctly

I'm currently wrapping up my bank account program, but I've ran into some problems en route to completion. The problem seems pretty easy to resolve, but I can't quite wrap my head around how I should go about actually fixing it.
I'll first include the assignment below:
Implement a class Account. An account has a balance, functions to add and withdraw money, and a function to inquire the current balance. Pass a value into a constructor to set an initial balance.
If no value is passed the initial balance should be set to $0.
Charge a $5 penalty if an attempt is made to withdraw more money than available in the account.
Enhance the Account class to compute interest on the current balance.
Implement a class Bank. This bank has two objects, checking and savings, of the type Account that was developed in the preceding exercise.
Implement four instance methods:
deposit(double amount, String account)
withdraw(double amount, String account)
transfer(double amount, String account)
printBalances()
Here the account string is "S" or "C". For the deposit or withdrawal, it indicates which account is affected. For a transfer it indicates the account from which the money is taken; the money is automatically transferred to the other account.
The only problem appears to be with actually storing the information for each account in the balance variable in the Account.cpp file. It just stays at 0, and that's why I feel this issue should be easy to fix. I'd imagine I'm just forgetting something very basic about class implementations, but that is why I am here! Now that I think about it, I think part of my confusion comes from the fact that I've implemented similar programs before but used only arrays instead of variables, and I did not experience this same problem. The data seemed to get stored into the array regardless, so this may be my problem? The code follows:
Account.h:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class Account
{
public:
Account();
Account(double balance);
void Add(double money);
void Withdraw(double money);
double GetBalance();
private:
double balance;
};
Account.cpp:
#include "Account.h"
// Penalty Fee Constant
const double PENALTY_FEE = 5.00;
Account::Account()
{
balance = 0.00;
}
Account::Account(double money)
{
balance = money;
}
void Account::Add(double money)
{
balance += money;
}
void Account::Withdraw(double money)
{
if(money > balance)
balance += PENALTY_FEE;
else
balance -= money;
}
double Account::GetBalance()
{
return balance;
}
Bank.cpp:
#include "Account.h"
void deposit(double, string);
void withdraw(double, string);
void transfer(double, string);
void printBalances();
int main()
{
string accountChoice;
int selection;
double transaction = 0;
// !!!!!!!!!!!!!!!!!!HAVE TO STILL COMPUTE INTEREST!!!!!!!!!!!!!!!!
cout << fixed << showpoint << setprecision(2);
do
{
cout << "Please make a selection:" << endl;
cout << "1.) Deposit" << endl;
cout << "2.) Withdraw" << endl;
cout << "3.) Transfer" << endl;
cout << "4.) Print balances" << endl;
cout << "5.) Quit" << endl;
cin >> selection;
if(selection == 1)
{
cout << endl << "Please select the account you would like to perform operations on(S or C):" << endl;
cin >> accountChoice;
cout << endl << "Please enter the amount to be deposited:" << endl;
cin >> transaction;
cout << endl;
deposit(transaction, accountChoice);
}
else if(selection == 2)
{
cout << endl << "Please select the account you would like to perform operations on(S or C):" << endl;
cin >> accountChoice;
cout << endl << "Please enter the amount to be withdrawn:" << endl;
cin >> transaction;
cout << endl;
withdraw(transaction, accountChoice);
}
else if(selection == 3)
{
cout << endl << "Please select the account you would like to perform operations on(S or C):" << endl;
cin >> accountChoice;
cout << endl << "Please enter the amount to be transferred:" << endl;
cin >> transaction;
cout << endl;
transfer(transaction, accountChoice);
}
else if(selection == 4)
printBalances();
else
cout << "Closing program -- Thank you for using the ATM teller!" << endl;
}while(selection != 5);
system("pause");
return 0;
}
void deposit(double amount, string account)
{
Account savings, checking;
if(account == "S" || account == "s")
savings.Add(amount);
else
checking.Add(amount);
}
void withdraw(double amount, string account)
{
Account savings, checking;
if(account == "S" || account == "s")
savings.Withdraw(amount);
else
checking.Withdraw(amount);
}
void transfer(double amount, string account)
{
Account savings, checking;
if(account == "S" || account == "s")
{
savings.Withdraw(amount);
checking.Add(amount);
}
else
{
checking.Withdraw(amount);
savings.Add(amount);
}
}
void printBalances()
{
Account savings, checking;
cout << "The current balance in savings is: " << savings.GetBalance() << endl;
cout << "The current balance in checking is: " << checking.GetBalance() << endl << endl;
}
I think it might be clearer overall if you declare another class 'Customer', and give them a name, customer number and a checking and saving account each. The Customers should be instantiated somewhere with process lifetime so that they are not deleted, eg. in a static container, eg std::map.
ATM, (sorry!), you seem to have some non-member functions that instantiate accounts, do things with them and then they are deleted upon function return.
You are creating a new Account object every time you need it. Of course it will be 0 when you print it as the default constructor initializes the balance to 0.
Rather when the App starts, as the user to identify his account or something and create a corresponding account instance. The instance need to be there throughout the whole time user operates on it.
So instantiate not in the methods but in the main function. And pass the instance to the methods as a way of modifying the instance as required.

C++ Adding sum of multiple function calls within a loop

I've been working on an assignment that calculates the total profit/loss for multiple stock sales via a looping function with information inputted by user for each stock sale. I did a thorough amount of googling to no avail. I was able to get the function working within the loop but I have not been able to figure out how to add the profit/loss from multiple sales - instead only displaying profit/loss for each individual function call. My function's algorithm checks out if you manually add the totals for each sale, just unclear on how to find the sum of multiple function calls.
Here is the sample data I'm suppose to enter that should display the total profit of $3324.00:
sale numberOfShares salePrice salesCommission purchasePrice purchaseCommission
1 25 15 7.50 5 2.50
2 100 2.50 12 1.75 8
3 1000 5.10 51 2 20
And my code thus far:
#include <iostream>
#include <iomanip>
using namespace std;
// Function prototype
double stockProfitFunction(double NS, double PP, double PC, double SP, double SC);
// Main Function
int main()
{
// Format output
cout << fixed << setprecision(2);
// Initialize variables
double profit,
numberOfShares,
salePrice,
saleCommission,
purchasePrice,
purchaseComission;
int numberOfSales;
// Get # of sales from user
cout << "Multiple Stock Profit Calculator\n--------------------------------\n\n";
cout << "How many sales do you wish to enter?: ";
cin >> numberOfSales;
cout << endl;
// Perform function in loop for number of sales
for (int i = 1; i <= numberOfSales; i++)
{
system("cls"); // Clears screen
cout << "Multiple Stock Profit Calculator\n";
cout << "(Currently entering stock sale #" << i << ")\n----------------------------------\n";
// Get information from user
cout << "Enter number of shares: ";
cin >> numberOfShares;
cout << "Enter sale price: ";
cin >> salePrice;
cout << "Enter sales commission: ";
cin >> saleCommission;
cout << "Enter purchase price: ";
cin >> purchasePrice;
cout << "Enter purchase commission: ";
cin >> purchaseComission;
//Calcualtes profit with function
profit = stockProfitFunction(numberOfShares, purchasePrice, purchaseComission, salePrice, saleCommission);
// Display "profit" or "loss" depending on positive or negative value returned by function
if (profit >= 0)
{
cout << "\n-----------------------\n";
cout << "You earned a profit of: $" << profit << endl;
cout << "(Press enter to input next sale)";
cin.get();
cin.get();
}
else
{
cout << "\n-----------------------\n";
cout << "You had a loss of: $" << profit << endl;
cout << "(Press enter to input next sale)";
cin.get();
cin.get();
}
}
return 0;
}
// Stock Profit Function, returns profit
double stockProfitFunction(double NS, double PP, double PC, double SP, double SC)
{
return ((NS * SP) - SC) - ((NS * PP) + PC);
}
Thanks for taking a look!
Initialize a variable to zero.
Each time you calculate a profit, add it to that variable.
Where desired, output the value of that variable.
By the way:
system("cls"); // Clears screen
That's a very bad habit to get into. Maybe on your machine, cls clears the screen, but you have no way to know what the cls command might do on someone else's machine. (On mine, there is no command called cls, the clear screen command is clear.) Unless you absolutely have no choice, you should strongly avoid using system in your C++ code.

C++ Values not been stored as needed

This code is from my "virtual ATM machine" program which deals with customers depositing, checking balance and withdrawing money from their account. When I deposit the money, it displays that it gets deposited.. But... here goes the code before I state my problem:
double bankAccount::deposit()
{
bankAccount b;
double amt;
system("cls");
cout << " ----------------------------------------------------------------------- \n";
cout << "| Customer Menu | \n";
cout << " ----------------- ----------------- ----------------- ----------------- \n";
cout << "\n\nYOUR CURRENT BALANCE: " << balance << endl;
cout << "\nEnter amount to deposit: ";
cin >> amt;
balance = (balance + amt);
cout << "\nAmount depositted successfully!" << endl;
cout <<"\nYOUR CURRENT BALANCE: " << balance;
getch();
customer_actions();
return balance;
}
"customer_actions()" being the main menu for the customers, when I go back on that screen and select the option to check balance, it displays as ZERO. Which means the values didn't get updated from the previous function. Here's my header file which consists of the class file:
#ifndef bank
#define bank
using namespace std;
class bankAccount
{
public:
int accNo;
int password;
double balance;
double withdrawamt;
double depositamt;
char name[20];
char address[40];
char username[10];
public:
double checkbalance();
double deposit();
double withdraw();
public:
bankAccount()
{
balance = 0; // Is this the reason?
}
};
#endif
I'm thinking, when the program switches from one menu to the other, the values get reset-ed. Any suggestions, dear folks?
Thanks in advance!
CUSTOMER_ACTIONS:
int customer_actions()
{
bankAccount b;
int cust_selection;
system("cls");
cout << " ----------------------------------------------------------------------- \n";
cout << "| Customer Menu | \n";
cout << " ----------------- ----------------- ----------------- ----------------- \n";
cout << " Please Select option to continue: \n" << endl << endl;
cout << "1) Check balance : Press 1" << endl;
cout << "2) Withdraw Cash : Press 2" << endl;
cout << "3) Deposit Cash : Press 3" << endl;
cout << "4) Transfer Cash : Press 4" << endl;
cout << "5) Return home : Press 5" << endl;
cout << "\nEnter option: ";
cin >> cust_selection;
switch(cust_selection)
{
case 1: b.checkbalance(); break;
case 2: b.withdraw(); break;
case 3: b.deposit(); break;
case 4: break;
case 5: main(); break;
}
}
Your problem (from what I can see) is that you are trying to create an infinite loop where the user can keep pressing making changes on the menu until they exit. However you are going about this by calling customer_actions() from within the deposit function.
Try creating an infinite loop in an outer method, then returning from deposit without calling customer_actions().
Following OP edit
Try this:
int main(...)
{
int result = 0;
while(result == 0)
{
result = customer_actions();
}
}
Now change the switch statement in customer_actions to be like this:
switch(cust_selection)
{
case 1: b.checkbalance(); break;
case 2: b.withdraw(); break;
case 3: b.deposit(); break;
case 4: break;
case 5: return 1; // This is the change
}
return 0;
The bank account b you declare in customer_action is just valid in function scope.
In addition:
customer_action manages given accounts by their interface, accounts should not "manage" customer_action (in your case, don't call it from deposit)
You could easily get a stack overflow the way you coded that.
Generally speaking you should try to avoid mixing up model (your accounts) view (the output) and controller (user input) - related code.
Create clean interfaces and call in in a structured manner.
In addition:
I first read your bold put question and afterwards attended the code.
The first thing I did then was was trying to find if there is local redefinition of double balance. There is none, but I should not even have had to do so, because there are means to avoid side-effects on instance member variables like balance.
Foremost - make them private, not public.
Then:
use a prefix like m_ so m_balance that would be or even m_dblBalance to indicate the type
or prefix all private variables with a _, so _balance that would be
and/or emphasize each usage of instance member vars by prefixing them with a redundant this->
Personally speaking I dislike 1. but use 2. for instance variables.
There are many more design and implementation issues, eg. I would discourage char[] for strings and recommend using std::string, but maybe you start by just ending the marriage of deposit() and customer_actions() you blessed.

Basic problems with writing functions. Program randomly skips to the end

I'm very new to writing functions. This is my first attempt at using call by reference parameters specifically for a homework assignment. This program should calculate how long it takes to pay off a loan based on the users input of the amount they borrow, their monthly payment and the interest rate. The program should make sure the user doesnt input a payment number less than monthly interest amount and check for negative integers etc.
The area I commented out was my first go before i attempted to turn all of that into a function that uses call by reference parameters. At that point the program ran fine and i got output within a dollar of what I was looking for. After i rewrote the program like this and tried to make it a function, the program compiles but break to the bottom cout statements after asking for the interest rate. I assume my problem is somewhere within the interest1 function where i convert the percent to a decimal but i cant figure out why it would skip the rest of the functions afterwards.
Thanks for any advice you might have on this issue or anything else that looks wrong with the program itself.
#include <iostream>
#include <fstream>
using namespace std;
double amount();
double interest1();
double pay(double amt, double interest);
void payoff(double monthly, double Minpayment,double borrow,double interest, double&
totalinterest,int& month);
int main()
{
double monthly,month,totalinterest;
cout << fixed;
cout <<showpoint;
cout <<setprecision(2);
double borrow=amount();
double interest=interest1();
double Minpayment=pay(borrow, interest);
void payoff(double monthly,double Minpayment,double borrow,double interest,double&
totalinterest,int& month);
/*
// cout << "What is the monthly payment amount? \n";
// cin >> monthly;
// if(monthly<Minpayment)
// {
// cout << "You must make payments of at least: " << Minpayment++ << endl;
// cout << "Because your monthly payment is " << Minpayment << endl;
// cout << "Dont get overwhelmed with debt!!!!!! \n";
// }
// else
//
// {
// int month = 1;
// double totalinterest=0;
// do
// {
// double Minpayment=pay(borrow, interest);
// borrow=(borrow+Minpayment)-monthly;
// totalinterest=totalinterest+Minpayment;
// month++;
// }while(borrow>monthly);
*/
cout << "Your debt will be paid off in " << month << " months \n";
cout <<" with a final payment of " << borrow << endl;
cout << "You paid " << totalinterest << " in interest. \n";
return 0;
}
double amount()
{
double borrow,amt;
do
{
cout << "How much money do you want to borrow? \n";
cin >> amt;
if(amt<1)
cout << "You must enter a positive number!";
}while(amt<1);
borrow = amt;
return borrow;
}
double interest1()
{
double rate;
do
{
cout << "What is the annual interest rate expressed as a percent? \n";
cin >> rate;
if(rate<1)
cout << "You must enter a positive number!";
}while(rate<1);
double interest = (rate/12)*.01;
return interest;
}
double pay(double borrow,double interest)
{
double Minpayment=borrow*interest;
return Minpayment;
}
void payoff(double monthly,double Minpayment,double borrow,double interest, double&
totalinterest,int& month)
{
cout << "What is the monthly payment amount? \n";
cin >> monthly;
if(monthly<Minpayment)
{
cout << "You must make payments of at least: " << Minpayment++ << endl;
cout << "Because your monthly payment is " << Minpayment << endl;
cout << "Dont get overwhelmed with debt!!!!!! \n";
}
else
{
int month = 1;
do
{
double Minpayment=pay(borrow, interest);
borrow=(borrow+Minpayment)-monthly;
double totalinterest=totalinterest+Minpayment;
month++;
}while(borrow>monthly);
}
}
When you call a function inside main, you don't need to specify parameter types anymore:
void payoff(double monthly,double Minpayment,double borrow,double interest,double&
totalinterest,int& month); //wrong
should be
payoff(monthly, Minpayment,borrow, interest, totalinterest, month);
You should put double& andint& to the function's parameter list when define the function like you did.