Compound Interest Function in C++ - c++

Ok, after working on this for an embarrassing number of hours, I think I came up with something less cringe-worthy to ya'll "real" programmers.
Allow me to submit my humble and probably awful code.
It totally works, but now my issue is that I'm trying to make it go back to an initial question if the response is a negative number. I got it to say, "Hey! Don't put in a negative number!", but then it goes to the next prompt. Here's my current output for a negative input:
** Welcome to the Consumer Loan Calculator **
How much would you like to borrow? $-100
Please enter a positive loan amount.
What is your annual percentage rate? %
...And for a positive input:
** Welcome to the Consumer Loan Calculator **
How much would you like to borrow? $100
How much would you like to borrow? $100
How much would you like to borrow? $
I want it to go back to "How much would you like to borrow?" if the user input is negative and only go to the next question if the input is positive. What am I doing wrong now?
#include <iostream>
#include <cmath>
#include <iomanip>
#include <cstdlib>
using namespace std;
void get_input (double &principal, double &APR, double mon_pay);
int main()
{
double loan; // principal
double APR; // APR
double mon_pay; //monthly payment
cout << "** Welcome to the Consumer Loan Calculator **"<<endl;
do {
cout << "How much would you like to borrow? $";
cin >>loan;
if (loan < 0)
cout <<"Please enter a positive loan amount.";
}
while (loan > 0);
cout << "What is your annual percentage rate? %";
cin >>APR;
cout << "What is your monthly payment? $";
cin >> mon_pay;
APR = APR/100;
get_input (loan, APR, mon_pay);
}
void get_input (double &principal, double &APR, double mon_pay)
{
double total, add=0; // Total payment
int tpay=1; //Total months of payment
while (principal > 0)
{
add = principal * (APR/100);
principal = ((principal+add) - mon_pay);
tpay++;
}
total = mon_pay + principal;
cout << "Your debt will be paid off after "<< tpay << " months, with a final payment of just $" <<setprecision(3)<<total<<endl;
cout <<"Don't get overwhelmed with debt!"<<std::endl;
}

this line is definately wrong:
while (int tp=1, double p <= double m, double sub--m)

Fundamentally, there are a lot of problems with this code. I would recommend for starts to eliminate all global variables. They'll make your code more confusing to debug and it's considered bad practice generally to use them.
Furthermore, I would choose more descriptive identifiers for your variables -- it'll make the logic less abstruse. For example, m is a poor choice for a variable name. Why not choose monthly_pay or something more clear?
Additionally, while loops take arguments that are boolean. What you've written doesn't make sense and I'm honestly not sure what the compiler would do if it isn't screaming now. My guess is that it would be in an infinite loop from the int tp=1 always evaluating to true.
Finally, it's worthwhile to learn to modularize code. Based on your code, I'd venture to say you're a beginner in the realm of code. It's very good practice (and follows in logic nicely) to modularize your code. What logical steps would you follow if you were doing this by hand?
Greet user
Get input
Do some calculations
Output to user
Say goodbye
If there are more details, expected outputs, etc., I'd recommend adding them to your question or risk being flagged as too broad.
Good luck on your homework.
erip
EDIT
Totally forgot about functions.
Functions, like in math, require arguments.
f(x) = x^2 + 2x - 1. The argument to this function is obviously x.
In programming, some functions require arguments as well.
Let's say you're trying to model this equation...
You might consider doing something like this:
#include <math.h>
double compound_interest(double r, int n, double t, double P)
{
return P*pow((1+ r/n), n*t);
}
So if you want to call this in your main
//insert header stuff, function declarations, etc.
int main()
{
double rate = 0.1, // 10%
time = 10.0, // 10 months
principle = 125.00, // $125.00
accumulated; // This is what we want to know
int payment_period = 12; // 12 months
accumulated = compound_interest(rate, payment_period, time, principle);
cout << "Total accumulated cost is " << accumulated << endl;
return 0;
}

Related

I need help making a buy function for a mock stock buying program

For a project I'm doing, I need to write c++ code for a buy, sell, and search function. I am very new to c++ so I was basically thrown into the deep end and told to look up other code for help as long as I give credit to where I got it from. A classmate has built the GUI while the other is working on a local database to use. I've written some code so far but i can already tell it is not up to what we need, many errors, and I've never written anything like this before. If possible, I would appreciate some help to look in the right direction,
Below is what i've tried so far. I'm trying to write this so that when a button is selected in our GUI, it will determine if the user has enough money to buy the stock, and if it does, add the stock to their owned stocks and subtract credits that are present. If not enough credits then it would not let the button be selectable or output "insufficient funds"
//buy
#include <iostream>
using namespace std;
int buyStock(double money, int stockAmnt, double stockPrice) {}
int main() {
int stockAmnt = stocks
double money = availableFunds
double stockPrice = price
if (availableFunds >= price)
{
availableFunds = availableFunds - price;
stocks++;
else {
cout << "Insuficent funds" << endl;
}
return money, stockAmnt, stockPrice
}
}

Cplusplus rewriting a code about dooflingy

so I wrote out this c++ program which works, but after submitting it, It was returned back saying it needs to be rewritten since it did not use adjacent_difference, the problem asked is as follows:
The Rinky Dooflingy Company records the number of cases of dooflingies produced each day over a four-week period. Write a program that reads these production levels and stores them in an STL container. The program should then find and display:
a. The lowest, highest, and average daily production level.
b. A sequence that shows how much the production level rose or fell each day.
c. A sequence that shows, for each day, the total number of dooflingies produced up to and including that day.
You must use an Standard Container and you must use standard algorithms to do all the calculations shown in a, b, and c above. Solutions not using a standard container and not using standard algorithms for calculations are not acceptable.
And my feed back was:
A standard algorithm (adjacent_difference) exists to calculate the daily changes but you don't use it.
Does not meet problem spec requiring the use of standard algorithms where available.
Please help, I'm stumped and tried to rewrite it, but haven't succeded
here is my code as follows:
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
int main(){
vector<int> product; //set up vector
cout<<"Please enter the number of cases of Dooflingies produced each day:\n"; //prompt user to enter amount produced in a day
for(int i=0; i<5; i++){ //math for vector
int temp;
cin>>temp;
product.push_back(temp);
}
cout<<"-------------------------------";
cout<<"\nHighest Production Level: " <<*std::max_element(product.begin(),product.end())<<"\n"; //display highest production level
cout<<"Lowest Production Level: " <<*std::min_element(product.begin(),product.end())<<"\n"; //display lowest production level
cout<<"Average Production Level: " <<std::accumulate(product.begin(),product.end(),0.0)/product.size()<< "\n"; //display average production level
cout<<"-------------------------------";
cout<<"\nProduction Level Influx:\n"; //display rise in production, used spaces to make it easier to see
for(int i=1; i<28; i++){ //math for vector
cout <<"Day " <<i<<": "<<product[i]-product[i-1]<<"\n";
}
int cumulative_sum[28]; //the cumulative sum of the whole program
std::partial_sum(product.begin(),product.end(),cumulative_sum);
cout<<"-----------------------------\n";
cout<<"Total Production Until:\n"; //total amount of dooflingies produced
for(int i=0;i<28; i++){
cout<<"Day " <<i+1<<": "<<cumulative_sum[i]<<"\n"; //math
}
return 0;
}
Thank you in advance

Trying to setup an array to store the last three deposits into bank account system

float deposit (float balance)
{
float amount[3];
system("cls");
cout<<"Enter the amount you wish to deposit"<<endl;
cin>>amount[3];
balance = balance + amount[3];
writeBalance(balance);
return balance;
}
//This is a function to allow the user to increase their balance
but when I enter an amount in the deposit section of the program a popup box comes up and says:
Run-Time Check Failure #2 - Stack around the variable 'amount' was corrupted.
any help would be great thanks
Since you have float amount[3];, you can only access amount[0], amount[1], and amount[2]. Any other index with give you undefined behaviour which is the cause of your program crash.
Also, never use a float to represent actual money. You'll only be accurate to about 7 significant figures. Using a double is unsafe too even though the accuracy (at around 15 significant figures) will be better. Your best bet is to use a currency type. Have a look at this question: Best way to store currency values in C++
You must enter each element of the array in a loop. Change the code the following way
float deposit (float balance)
{
const size_t N = 3;
float amount[N];
system("cls");
cout<<"Enter the amount you wish to deposit"<<endl;
for ( size_t i = 0; i < N; i++ )
{
cin>>amount[i];
balance = balance + amount[i];
}
writeBalance(balance);
return balance;
}
Though in fact there is no need to use the array. You could enter data in one regular variable.

How do I avoid using arrays?

My professor wants us to write a program without using arrays or vectors like this:
Write a program using functions that calculates and prints parking charges for each of the n customers who parked their cars in the garage.
Parking rates:
a parking garage charges a $5.00 minimum fee to park for up to five hours.
the garage charges an additional $0.50 per hour for each hour or part thereof in the excess of five hours
the maximum charge for any given 24hr period is $10.00. Assume that no car parks longer that 24 hours at a time.
You should enter the hours parked for each customer. Your program should print the results in a neat tabular format and should calculate and print the total of your receipts.
The program output should look like this:
car------Hours------Charge
1--------2.00--------$5.00
2--------5.00--------$5.00
3--------5.30--------$5.50
etc.
total: 3---12.30----$15.50
I only managed to get this far:
include <iostream>
include <conio.h>
include <cmath>
include <iomanip>
using namespace std;
double calculate(double);
int main()
{
double hours,charge;
int finish;
double sumhours;
sumhours=0;
finish=0;
charge=0;
int cars;
cars=0;
do
{
cout<<"Enter the number of hours the vehicle has been parked: "<<endl;
cin>>hours;
cars++;
sumhours+=hours;
finish=cin.get();
if(hours>24)
{
cout<<"enter a time below 24hrs."<<endl;
cars--;
sumhours=sumhours-hours;
}
}
while(finish!=EOF);
double total=calculate(hours);
cout<<total<<": "<<(cars-1)<<": "<<sumhours;
while(!_kbhit());
return 0;
}
double calculate(double time)
{
double calculate=0;
double fees;
if(time<=5)
return 5;
if(time>15)
return 10;
time=ceil(time);
fees=5+(.5*(time-5));
return calculate;
}
Since this is homework, here is an algorithm:
1. Print header.
2. Clear running total variables.
3. While not end of file
3.1 read a record.
3.2 print record contents
3.3 add record field values to running total variables (Hint! Hint!)
3.4. end-while
4. print out running total variables.
You may have to do some additional calculations with the running total variables, especially for averages.
Edit 1: Example of a running total variable
int sum = 0; // This is the running total variable.
const unsigned int QUANTITY = 23;
for (unsigned int i = 0; i < QUANTITY; ++i)
{
cout << "Adding " << i << " to sum.\n";
sum += i;
}
cout << "Sum is: " << sum << "\n";
cout.flush();
In this example, the data 'i' is not stored only used. The sum variable is a running total.
Look for similarities in your assignment.
Edit 2: Example of detecting end of input on cin
char reply = 'n';
while (tolower(reply) != 'y')
{
cout << "Do you want to quit? (y/n)";
cout.flush();
cin >> reply;
cin.ignore(1000, '\n'); // Eat up newline.
}
cout << "Thanks for the answer.\n";
cout.flush();
Since you can't use arrays or vectors, I think you should print the parking data for each car as it's being processed. Pseudocode:
While more cars:
Read data for next car
Calculate cost
Print data
Add to running totals
End while
Print totals
On every iteration, generate the relevant output, but don't stream it to std::cout. Instead, stream it to a std::stringstream object. Then, at the end, stream that object to std::cout. The maths can be done simply by maintaining a running accumulation of the input values.
This, of course, assumes that using a std::stringstream is not considered "cheating" in the context of this homework exercise.
You can try storing your values in a linked list structure instead of an array. Linked lists work great for dynamic storage.
Try this tutorial, http://www.cprogramming.com/tutorial/lesson15.html
My suggestion then is to use a recursive method, the method first accepts input, asks if there is any more input. If there is more input, it then calls itself. If there is no more input, it outputs it's current car and then returns a sum that's added so far in a structure.
The only problem with this method is that it would output entered cars in reverse of input, but it would do so without an array or a file to save to.

I want to make an 'if' statement that if a variable is less the 80 t=0 but if the variable is over t=x-80

hi i just started to learn c++. I'm trying to figure out how to make a variable change depending on another variable. It shows a strange answer when i try it idk where its getting it from. anyways i'll just put my code in here and hope someone understands what i am doing.
#include <iostream>
long int mult (float hours,float payrate,float tax,float overtimerate,float overtimehours,float overtimeday,float insurance);
int main()
{
float insurance;
float hours;
float payrate;
float tax;
float overtimerate;
float overtimehours;
float overtimeday;
insurance=.81;
overtimehours=0;
overtimerate=1.5;
tax=4.93372123545367;
std::cout<<"Paycheck calculator\n";
std::cout<<"Enter your hours\n";
std::cin>>hours;
std::cin.ignore();
std::cout<<"Did you work over 8 hours in a day?\n If so enter how much? If none enter 0\n";
std::cin>>overtimeday;
if (hours>80)
{
overtimehours=((hours - 80)+overtimeday);
}
std::cout<<overtimehours+overtimeday<<"\n";
std::cout<<"Enter your pay rate\n";
std::cin>>payrate;
std::cin.ignore();
std::cout<<"Your paycheck should be approximately: "<<((overtimeday+overtimehours)*(overtimerate*payrate
))+(((hours-overtimehours)*payrate)-((((hours-(overtimeday+overtimehours))*payrate)/tax)
-insurance))<<"\n";
}
In the expression:
x=(t*w)+((hours-t)*rate);
You are using t, even though t has never been set.
t will be undefined at this point, and may have any value.
Same thing with hours and rate.
Your compiler should have given you warnings about uninitialized variables.
Edit looking at your code more, it seems you are attempting to establish "rules" for hour, rate and t, then later fill in the values, expecting those "rules" will be preserved.
C++ does not work like this. It is a sequential language, meaning that each instruction is executed once, as it is read, top-to-bottom.
You need to change your program flow to be:
Gather variables
Do calculations and logic
Output the answers.
It seems you reversed steps 1 and 2, trying to setup the calculations before gathering the variables.
You need to assign a value to t before using it. Saying float t; will not actually give it a meaningful value. Ditto hours and rate. Assign them before doing x=(t*w)+((hours-t)*rate);.
you haven't initialized hours (it is always good practice to initialize all your local variables)
note also that 'hours' is of type float and these are not represented exactly so your compare with 80 may yield a different result than you expected.
I see you have a function declared:
int mult (float x,float t,float w,float hours, float rate,float z);
that you never do anything with. I think the code you have in main mostly belongs in mult and that your main should either assign values to these variables or prompt the user for them and read them from cin. You do this for some variables later on, but then never use what you read in.
I agree with #quantumSoup btw, your variables are poorly named. Also, your code is really in an odd order. This makes it hard to guess what you want.
Other answers pointed out very serious flaws in your code, so you should take them seriously, but there is one thing, the topic suggests you are struggling with, that wasn't explained. Let me try.
I think you are struggling with a way to calculate overtime. You take an input from a user, that indicates the number of hours of work. If that number is less or equal to 80, there is no overtime. Otherwise the overtime is equal to hours - 80, right?
You can express the logic in C++ like this:
float hours;
float overtime;
//....
cout<<"enter the amount of hours you have worked\n";
cin>>hours;
if(hours > 80)
{
overtime = hours - 80;
}
else
{
overtime = 0;
}
If you initialize the overtime variable to 0, you can omit the else part.
float hours;
float overtime = 0;
//....
cout<<"enter the amount of hours you have worked\n";
cin>>hours;
if(hours > 80)
{
overtime = hours - 80;
}