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.
Related
This program accepts feet and inches and converts them into meters and centimeters.
My main concern is outputting the right values, all other help with the other two problems would be greatly appreciated!
There are several things I am having problems with, I will list them in order of importance:
I am outputting the same values that is being inputted into the computer ( no mathematical operations I have constructed are taking place I believe. Example: I input 12 feet 6 inches and it returns 12 meters 6 centimeters
My do-while loop is not presenting the option to input y/n to repeat the program (I believe I must have my do-while loop in the wrong place)
I don’t believe that the output would be presented correctly even if the mathematical operations were to be working. For example: If I input 12 feet 9 inches this will equate to 3.65 meters and 22.86 centimeters but the problem here is that the .65 in the 3.65 meters can be added to centimeters so that it fully converts into a whole number in meters with the remainder added into centimeters (b/c 1 meter = 100 centimeters) but unfortunately I can not use the modulos operator (%) because this only works with integer operators and I don’t think a "static cast" would work here if I wanted to convert meters of data type double to data type int so that the modulos operator will work
renaming variables in calValues function
#include <iostream>
using namespace std;
void getNumbers(double& input1, double& input2);
void calcValues(double& variable1, double& variable2);
void showResults(double& result1, double& result2);
int main()
{
double firstNum, secondNum;
char ans;
cout << "This program accepts feet and inches " << endl;
cout << "to convert them into meters and centimeters." << endl;
do
{
getNumbers(firstNum, secondNum);
calcValues(firstNum, secondNum);
showResults(firstNum, secondNum);
} while (ans == 'y' || ans == 'Y');
cout << "Thank you for using the program." << endl;
return 0;
}
void getNumbers(double& input1, double& input2)
{
cout << "Enter in number of feet:" << endl;
cin >> input1;
cout << "Enter in number of inches:" << endl;
cin >> input2;
}
void calcValues(double& variable1, double& variable2)
{
const double METER = 0.3048, CENTI = 100, INCH = 12;
double finalMeter, finalCenti, tempFeet, tempMeter;
finalMeter = (variable1 * METER);
tempFeet = (variable2 / INCH);
tempMeter = (tempFeet * METER);
finalCenti = (tempMeter * CENTI);
}
void showResults(double& result1, double& result2)
{
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << "The feet and inches you entered equates to " << endl;
cout << result1 << " meters and " << result2 << " centimeters." << endl;
cout << "Would you like to enter in " << endl;
cout << "new values for feet and inches? (y/n)" << endl;
}
In calcValues you must actually assign to variable1 and variable2 if you want to change what they refer to, e.g.
void calcValues(double& variable1, double& variable2)
{
const double METER = 0.3048, CENTI = 100, INCH = 12;
double finalMeter, finalCenti, tempFeet, tempMeter;
finalMeter = variable1 * METER;
tempFeet = variable2 / INCH;
tempMeter = tempFeet * METER;
finalCenti = tempMeter * CENTI;
variable1 = finalMeter;
variable2 = finalCenti;
}
You really don't need all those brackets either.
PS I suspect that the calculation is wrong, but I'll leave you to sort that out.
char ans;
void calcValues(double& variable1, double& variable2)
You need to initialize/input ans and variables.
Ok I believe I am interacting with the "variables" now (terminology may be wrong) I am able to see my output change as opposed to showing the same numbers I inputted in the beginning but I still am unsure that, in the showResults function where I initialize my finalMeter and finalCenti to the function calcValues, the parameters are right because I want to interact with only one part of the function calcValues (just meters for example) and not both parts and I assume if I include calcValues(input1, input2) that this will cause both numbers to be included in the output and the compiler i am using (repl) will not allow me to just pass only one parameter for example calcVaules(input1) I assume this will allow me to display only the 1st number.
I am playing around with this code alot and drawing from other examples to see how they formatted their code but it has to be that I do not understand the full logic of where the data is being moved (variable to variable) I know the pass by reference applies to the location of the variable itself as opposed to passing a copy of it in a pass by value (I may have butchered the definition/my understand of these concepts)
Once again all the help is very much appreciated and I understand what yall are saying but it is hard to translate that into a workable code snippet that would allow this program to run,
thanks again :)
#include <iostream>
using namespace std;
void getNumbers(double& input1, double& input2);
double calcValues(double& variable1, double& variable2);
void showResults(double& output1, double& output2);
int main()
{
double firstNum, secondNum;
char ans;
cout << "This program accepts feet and inches " << endl;
cout << "to convert them into meters and centimeters." << endl;
do
{
getNumbers(firstNum, secondNum);
calcValues(firstNum, secondNum);
showResults(firstNum, secondNum);
}while (ans == 'y' || ans =='Y');
cout << "Thank you for using the program." << endl;
return 0;
}
void getNumbers(double& input1, double& input2)
{
cout << "Enter in number of feet:" << endl;
cin >> input1;
cout << "Enter in number of inches:" << endl;
cin >> input2;
}
double calcValues(double& meters, double& centimeters)
{
const double METER = 0.3048, CENTI = 2.54, INCH = 12;
meters = (meters * METER);
centimeters = (centimeters * CENTI);
}
void showResults(double& input1, double& input2)
{
double finalMeter, finalCenti;
finalMeter = calcValues(input1, input2);
finalCenti = calcValues(input1, input2);
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << "The feet and inches you entered equates to " << endl;
cout << finalMeter << " meters and " <<
finalCenti << " centimeters." << endl;
cout << "Would you like to enter in " << endl;
cout << "new values for feet and inches? (y/n)" << endl;
}
I have created an solution that compiles correctly, but when I enter in the required input it provides only a value of '0' which is not correct. It started when I amended the code to have exception handling but for some reason now, the code no longer processes. The first three input values can be anything and it will still output '0' when run. Thoughts?
#include <iostream>
#include <cmath>
#include <string>
#include <sstream>
#include <stdexcept>
using namespace std;
class MortgageCalc
{
private:
double loan, interest;
int years;
public:
MortgageCalc() = default;
void setLoan(double l) { loan = l; } //mutator
void setIntrest(double i) { interest = i; } //mutator
void setYears(short y) { years = y; } //mutator
double getMonthlyDue(double term) { return ((loan * ((interest / 100) / 12) * term) / (term - 1)); } //constructor to run math calculation on montly loan amou
double getTotalDue(double term) { return (getMonthlyDue(term) * (years * 12)); } //constructor to compute total amount with interest
double getTotalInt(double term) { return (getTotalDue(term) - loan); }
};
int main()
{
MortgageCalc mort1;
int choice = 0;
int years = 0;
double term(0), loan(0), interest(0);
cout << "Enter the total loan amount on your mortgage loan: $"; //established loan variable
{
std::string loan;
try
{
cin >> loan;
}
catch (string loan) //Exception for comma in 'loan' input by user
{
if (loan.find_first_not_of("0123456789.") != std::string::npos) // npos invalid pseudo-index
{
std::cerr << "bad input, must use whole numbers only\n" << endl;
return 1;
}
std::istringstream ins(loan); // Converts the string into a number without punctuation
ins >> loan;
}
}
// cout << "Loan amount cannot be negative. Enter the amount: ";
mort1.setLoan(loan);
cout << "Enter the interest rate (in whole #'s only): "; //establishes interest rate variable
cin >> interest; {
if (interest <= 0) { //example if you put 0 or negative # an exception will throw
throw std::invalid_argument("received negative value"); //example #2 of negative throw exception
}
}
// cout << "Interest rate cannot be negative. Enter the amount: ";
mort1.setIntrest(interest);
cout << "Enter the length of the loan in years: "; //establishes term of payments
while (!(cin >> years) || years < 0)
cout << "Remainder of loan period cannot be negative. Enter the amount: ";
mort1.setYears(years);
term = pow((1 + ((interest / 100) / 12)), (12 * years)); //simple interest calculation with power calc to establish whole number translation
while (choice != 3) //loop for menu options and clean function exit
{
cout << endl;
cout << "Program to Calculate Mortgage Payments" << endl <<
"1. Monthly Payment" << endl <<
"2. Total Payment" << endl <<
"3. Exit" << endl << endl <<
"Enter an option above: ";
cin >> choice;
if (choice == 1)
cout << "Monthly payment due is " << mort1.getMonthlyDue(term) << "." << endl;
else if (choice == 2)
cout << "Total amount for entire loan payments plus interest is $" << mort1.getTotalDue(term) << "." << endl <<
"Total Interest Paid for this loan amount $" << mort1.getTotalInt(term) << "." << endl;
}
return 0;
}
Your problem is that when you do
mort1.setLoan(loan);
loan will always be 0 unless cin >> loan; throws an std::sting. When you use
{
std::string loan;
try
{
cin >> loan;
}
catch (string loan) //Exception for comma in 'loan' input by user
{
if (loan.find_first_not_of("0123456789.") != std::string::npos) // npos invalid pseudo-index
{
std::cerr << "bad input, must use whole numbers only\n" << endl;
return 1;
}
std::istringstream ins(loan); // Converts the string into a number without punctuation
ins >> loan;
}
}
You have your conversion code from a string into the double1 in the catch statement. You will only ever enter that statement if cin >> loan; throws a std::string which I do not believe will ever happen. Since you never actually update the value of loan in main it stays at the 0 you initialized it with.
You should only be doing error handling in the catch block. The code to convert the string to a double should be handled outside the catch block. I think you need to revisit how exceptions work and you should also look into how scopes can hide names from the outer scope.
1 This is also not going to work since you are hiding the double loan from main with the string loan declared inside the sub scope. You need to use different names for the variables in the sub scope.
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.
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
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.