C++ Why is this outputting the wrong compound interest? - c++

I've been trying to figure this out for sometime and I think it has something to do with the values I'm using for the calculations. I'm not exactly familiar with compound interest so I'm not sure were I'm going wrong. Any help would be appreciated.
#include <iostream>
#include <cmath>
using namespace std;
double interest_credit_card(double initial_balance, double interest_rate, int payment_months);
// Calculates interest on a credit card account according to initial balance,
//interest rate, and number of payment months.
int main ()
{
double initial_balance, interest_rate;
int payment_months;
char answer;
do
{
cout << "Enter your initial balace: \n";
cin >> initial_balance;
cout << "For how many months will you be making payments?\n";
cin >> payment_months;
cout << "What is your interest rate (as a percent)?: %\n";
cin >> interest_rate;
cout << endl;
cout << "You will be paying: $ " << interest_credit_card( initial_balance, interest_rate, payment_months) << endl;
cout << "Would you like to try again? (Y/N)\n";
cin >> answer;
}while (answer == 'Y' || answer == 'y');
cout << "Good-Bye.\n";
return 0;
}
double interest_credit_card(double initial_balance, double interest_rate, int payment_months)
{
double compound_interest, compounding, compounding2, compounding3, compounding4;
while(payment_months > 0)
{
initial_balance = initial_balance + (initial_balance * interest_rate/100.0);
compounding = (interest_rate /12);
compounding2 = compounding + 1;
compounding3 = interest_rate * (payment_months/12);
compounding4 = pow(compounding2, compounding3);
compound_interest = initial_balance * compounding4;
initial_balance = initial_balance + compound_interest;
payment_months--;
}
return initial_balance;
}
Inputs and expected outputs:
Enter your initial balance: 1000
For how many months will you be making payments?: 7
What is your interest rate (as a percent)?: 9
You will be paying: $1053.70

It looks like you were trying a bunch of things and then left them in. The first solution you tried was almost right, you just forgot "/12":
double interest_credit_card(double initial_balance, double interest_rate, int payment_months)
{
while (payment_months > 0)
{
initial_balance = initial_balance + (initial_balance * interest_rate / 100.0/12);
payment_months--;
}
return initial_balance;
}
With a little better style:
double interest_credit_card(double initial_balance, double interest_rate, int payment_months)
{
double total_payment = initial_balance;
double monthly_rate = interest_rate / 100.0 / 12;
for (int month = 1; month <= payment_months; ++month)
total_payment += total_payment * monthly_rate;
return total_payment;
}

Related

Don't understand why output is incorrect

I'm currently doing a Zybooks lesson for my C++ class and we're going over while loops. In this question, it wants me to calculate how many years it takes for a bank account to double it's initial balance. There is also an annual contribution added. My code is as follows:
#include <iostream>
using namespace std;
int main()
{
const double RATE = 5;
const double INITIAL_BALANCE = 10000;
const double TARGET = 2 * INITIAL_BALANCE;
cout << "Annual contribution: " << endl;
double contribution;
cin >> contribution;
double balance = INITIAL_BALANCE;
int year = 0;
while (balance < TARGET)
{
year++;
double interest = balance * RATE / 100;
balance = balance + interest + contribution;
}
cout << "Year: " << year << endl;
cout << "Balance: " << balance << endl;
return 0;
}
I used this as an answer but was met with this unexpected result:
Output differs. See highlights below.
Input
100
Your output
Annual contribution:
Year: 13
Balance: 20627.8
Expected output
Annual contribution:
Year: 13
Balance: 20527.8
I see the expected output and your output differs by a 100, i.e. your contribution. Maybe the evaluation system doesn't add annual contribution once your target is reached. The below code gets your required output, but I think your code should have been the correct answer.
#include <iostream>
using namespace std;
int main()
{
const double RATE = 5;
const double INITIAL_BALANCE = 10000;
const double TARGET = 2 * INITIAL_BALANCE;
cout << "Annual contribution: " << endl;
double contribution;
cin >> contribution;
double balance = INITIAL_BALANCE;
int year = 0;
while (balance < TARGET)
{
year++;
double interest = balance * RATE / 100;
balance = balance + interest;
if (balance < TARGET) {
balance += contribution;
}
}
cout << "Year: " << year << endl;
cout << "Balance: " << balance << endl;
return 0;
}
The problem is that you're making a contribution after the 13th year even though the target has been reached.
I would restructure to something like this, in order to only check the condition once:
while (true)
{
year++;
double interest = balance * RATE / 100;
balance += interest;
if (balance >= TARGET)
{
break;
}
balance += contribution;
}
This is because the last time the loop is being executed (at year=13), balance is less than TARGET but, after adding a contribution and interest into it, it jumps out of the loop with contribution and interest added to it.
So, the solution can be to use an if statement within the while loop to check if it exceeds the TARGET; if it does, then don't add contribution into it.
Replace your while loop with the following:
while (balance < TARGET)
{
year++;
double interest = balance * RATE / 100;
balance = balance + interest;
if (balance < TARGET) {
balance += contribution;
}
}

Calculations wont display in output

I'm a student in a basic programming class and I'm trying to complete this program for a class assignment. It's a simple program that calculates compounded interest by the inputs of the user. However, when writing the code, I noticed that the the result is 0 even though based on the input I would expect otherwise. Could anyone tell me why the program isn't showing results?
#include <iostream>
#include <cmath>
using namespace std;
// Declarations of Prototype
void futureValue(double* presentValue, float* interestRate, int* months, double* value);
// List of variables
double presentValue = 0;
float interestRate = 0;
double value = 0;
int months = 0;
// Start of Main function
int main(void)
{
cout << "What is the current value of the account?";
cin >> presentValue;
cout << "How many months will Interest be added to the account?";
cin >> months;
cout << "And what will be the Interest Rate of the account?";
cin >> interestRate;
cout << "After " << months << " months, your account balence will be $" << value << ".";
return 0;
}
void futureValue()
{
if (presentValue <= 0)
{
cout << "I'm sorry, you must have a current balence of more than 0.00 dollars to calculate.";
return;
}
else
{
value = presentValue * pow(interestRate + 1, months);
return;
}
}
Yes. You are not calling the futureValue function which would compute the value for you. Due to the value not being computed, it remains 0. Fix:
#include <iostream>
#include <cmath>
using namespace std;
// Declarations of Prototype
void futureValue(double* presentValue, float* interestRate, int* months, double* value);
// List of variables
double presentValue = 0;
float interestRate = 0;
double value = 0;
int months = 0;
// Start of Main function
int main(void)
{
cout << "What is the current value of the account?";
cin >> presentValue;
cout << "How many months will Interest be added to the account?";
cin >> months;
cout << "And what will be the Interest Rate of the account?";
cin >> interestRate;
futureValue(); //Here we compute the value
cout << "After " << months << " months, your account balence will be $" << value << ".";
return 0;
}
void futureValue()
{
if (presentValue <= 0)
{
cout << "I'm sorry, you must have a current balence of more than 0.00 dollars to calculate.";
return;
}
else
{
value = presentValue * pow(interestRate + 1, months);
return;
}
}

Trying to add while loop to this codeblock

SOLVED 11/19/2017 # 10:20PM
This is the codeblock I'm working on, and I need to implement a while loop to run it infinitely until the user is satisfied. I'm not sure if gross_pay should be in the condition or if something else needs to be there. I keep on getting this error code. (error C4700: uninitialized local variable 'gross_pay' used)
// GrossPay.cpp : Defines the entry point for the console application.
//int temp = 0;
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main()
{
double hourly_rate;
double hours;
double gross_pay;
while ( gross_pay >= 1 ) {
printf("Please input the hourly rate of the employee: ");
cin >> hourly_rate;
printf("Please input the number of hours worked by the employee: ");
cin >> hours;
if (hours <= 40)
{
gross_pay = hours * hourly_rate;
}
else
{
gross_pay = (40 * hourly_rate) + (hours - 40) * (hourly_rate * 1.5);
}
cout << "The gross pay of this employee is $" << gross_pay << "." << endl;
system("pause");
return 0;
}
}
Solution:
// GrossPay.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
double hourly_rate;
double hours;
double gross_pay = 1;
while (gross_pay >= 1) {
printf("Please input the hourly rate of the employee: ");
cin >> hourly_rate;
printf("Please input the number of hours worked by the employee: ");
cin >> hours;
if (hours <= 40)
{
gross_pay = hours * hourly_rate;
}
else
{
gross_pay = (40 * hourly_rate) + (hours - 40) * (hourly_rate *
1.5);
}
cout << "The gross pay of this employee is $" << gross_pay << "." <<
endl;
}
return 0;
}
Every variable should be initialized before you are using for an operation otherwise the result may not be same as you expected.
Rewrite as double gross_pay = 1;
If you don't specify an initialization value then the value for double gross_pay is undefined. It will set to 0 for global variable.
The error message says everything, you have to initialize gross_pay first, otherwise its value is undefined
double gross_pay = 1;
Or you can change while loop to do-while
do {
printf("Please input the hourly rate of the employee: ");
cin >> hourly_rate;
.....
.........
} while ( gross_pay >= 1 );

C++ Airfare Charge Calculation project

I have to create a program to calculate charges for airfare. It's a simple program so far and I am not done adding to it, but every time I run it the result turns out to be 0. Is there something missing in my code? I am a beginner and I would appreciate any advice on improving my code. Thank you.
#include <iostream>
using namespace std;
void main () {
int distance = 0;
int num_bags= 0;
int num_meals= 0;
double distance_price = distance * 0.15;
double bag_price = num_bags * 25.00;
double meal_price = num_meals * 10.00;
double total_airfare = 0.00;
cout << "CorsairAir Fare Calculator" << endl;
cout << "Enter the distance being travelled: " << endl;
cin >> distance;
cout << "Enter number of bags checked: " <<endl;
cin >> num_bags;
cout << "Enter the number of meals ordered: " << endl;
cin >> num_meals;
total_airfare = (distance_price + bag_price + meal_price);
cout << total_airfare;
}
Your confusion is completely understandable - the piece you're missing is that when you assign a variable, you're assigning the left side to the result of the right side at that moment in time. It's not like algebra, where you say f(x) = x + 5 and f(x) is always whatever x + 5 is.
So, you assign double distance_price = distance * 0.15 when distance is 0 (which you just initialized). distance_price remains 0 even after you ask for input and change distance.
Do your price calculations after you ask for input, and everything will work just fine.
You are calculating the distance_price bag_price meal_price with default values i.e. 0 not with the value which you took from user.
Below code works fine and you won't see the issue.
#include <iostream>
using namespace std;
// My compiler did not allow void main so used int main
int main () {
int distance = 0;
int num_bags= 0;
int num_meals= 0;
double distance_price ;
double bag_price ;
double meal_price;
double total_airfare;
cout << "CorsairAir Fare Calculator" << endl;
cout << "Enter the distance being travelled: " << endl;
cin >> distance;
cout << "Enter number of bags checked: " <<endl;
cin >> num_bags;
cout << "Enter the number of meals ordered: " << endl;
cin >> num_meals;
distance_price = distance * 0.15;
bag_price = num_bags * 25.00;
meal_price = num_meals * 10.00;
total_airfare = 0.00;
total_airfare = distance_price + bag_price + meal_price;
cout << total_airfare;
return 0;
}
Result
CorsairAir Fare Calculator
Enter the distance being travelled:
200
Enter number of bags checked:
2
Enter the number of meals ordered:
2
100

C++ Calculation Problem, Always returns $0

I have to display and loop a menu, allowing the customer to make multiple orders for peanuts, movies, or books. The menu displays fine, but the quantity doesn't go down to the calculations part of my code. Everytime I enter a quantity for anything and checkout it returns $0. I have no idea why this is happening I don't see anything wrong with my code, but obviously there is. Do you guys have any suggestions on what to do based on looking at what I have?
#include <iostream>
#include <cstdlib>
using namespace std;
//function declarations
void displayMenu();
//constant statements
const double BOOK_PRICE = 9.00; //price per book
const double BOOK_SHIPPING = 1.06; //shipping per book
const double MOVIE_PRICE = 13.99; //price per movie
const double MOVIE_SHIPPING = .05; //shipping per movie subtotal
const double PEANUT_PRICE = 1.80; //price of peanuts per pound
const double SHIPPING_PRICE = .50; //shipping of peanuts per lb
int main()
{
//declaration statements
int numBooks = 0; //# of books purchased
int numMovies = 0; //# of movies purchased
double numPeanuts = 0.0; //# of peanuts per pound
double bookSubtotal = 0.0; //subtotal of books
double movieSubtotal = 0.0; //subtotal of movies
double peanutSubtotal = 0.0; //subtotal of peanuts
int totalBooks = 0; //running total of books
int totalMovies = 0; //running total of movies
double totalPeanuts = 0.0; //running total of peanuts
int userChoice = 0; //user input
double totalPrice = 0.0; //final price
while (userChoice != 4)
{
displayMenu();
cout << "Enter a menu choice: ";
cin >> userChoice;
if (userChoice == 1)
{
cout << "Please enter the number of books: ";
cin >> numBooks;
totalBooks = totalBooks + numBooks;
}
else if (userChoice == 2)
{
cout << "Please enter the number of movies: ";
cin >> numMovies;
totalMovies = totalMovies + numMovies;
}
else if (userChoice == 3)
{
cout << "Please enter the pounds of peanuts as a decimal: ";
cin >> numPeanuts;
totalPeanuts = totalPeanuts + numPeanuts;
}
else if (userChoice == 4)
{
break;
}
else
{
cout << "Invalid Input" << endl;
}
}
//computations
bookSubtotal = (totalBooks * BOOK_PRICE) + (totalBooks * BOOK_SHIPPING);
movieSubtotal = (totalMovies * MOVIE_PRICE * .05) + (totalMovies * MOVIE_PRICE);
peanutSubtotal = (PEANUT_PRICE * totalPeanuts) + (totalPeanuts * .5);
totalPrice = bookSubtotal + movieSubtotal + peanutSubtotal;
cout << "The total price is $" << totalPrice << endl;
system("PAUSE");
return 0;
}//end of main
void displayMenu()
{
cout << "1 Books" << endl;
cout << "2 Movies" << endl;
cout << "3 Peanuts" << endl;
cout << "4 Checkout" << endl;
}//end of displayMenu
The problem is in the cin >> - you found the answer yourself when you say that the book count is zero. I suggest you try to put << endl after each cout << .... Other solution is to use _flushall(); after each cout.