C++ Compound Interest Exercise
Posted
by
Lameste
on Stack Overflow
See other posts from Stack Overflow
or by Lameste
Published on 2014-08-24T16:10:15Z
Indexed on
2014/08/24
16:20 UTC
Read the original article
Hit count: 187
c++
I'm a beginner trying to learn C++ using "C++ Primer Plus Sixth Edition".
I'm on Chapter 5, going over loops. Anyways I was doing this programming exercise from the book, the problem is:
Daphne invests $100 at 10% simple interest.That is, every year, the investment earns 10% of the original investment, or $10 each and every year: interest = 0.10 × original balance At the same time, Cleo invests $100 at 5% compound interest.That is, interest is 5% of the current balance, including previous additions of interest:
interest = 0.05 × current balance
Cleo earns 5% of $100 the first year, giving her $105.The next year she earns 5% of $105, or $5.25, and so on.Write a program that finds how many years it takes for the value of Cleo’s investment to exceed the value of Daphne’s investment and then displays the value of both investments at that time.
Here is the code I have written for this exercise, I'm not getting good results though.
#include <iostream>
#include <array>
double Daphne(int, double, double);
double Chleo(double, double);
int main() {
using namespace std;
int p = 100; //Principle
double i1 = 0.1; // 10% interest rate
double i2 = 0.05; // 5% interest rate
double dInv = 0; //Daphnes investment
double cInv = 0; // Chleos investment
int t=1; //Starting at year 1
double s1 = 0; //Sum 1 for Daphne
double s2 = 0; // Sum 2 for Chleo
s1 = p + 10; //Initial interest (base case after year 1) for Daphne
s2 = p + (i2*p); //Initial interest (base case after year 1) for Chleo
/*cout << s1 << endl;
cout << s2 << endl;*/
while (cInv < dInv) {
dInv = Daphne(p, i1, s1);
cInv = Chleo(i2, s2);
t++;
}
cout << "The time taken for Chleos investment to exceed Daphnes was: " << t << endl;
cout << "Daphnes investment at " << t << " years is: " << dInv << endl;
cout << "Chleos invesment at " << t << " years is: " << cInv << endl;
system("pause");
return 0;
}
double Daphne(int p, double i, double s1) {
s1 = s1 + (p*i);
return s1;
}
double Chleo(double i, double s2){
s2 = s2 + (s2*i);
return s2;
}
Output from console:
The time taken for Chleos investment to exceed Daphnes was: 1
Daphnes investment at 1 years is: 0
Chleos invesment at 1 years is: 0
Press any key to continue . . .
Can anyone explain why I'm getting this current result? The while loop is supposed to continue executing statements until Chleo's investment exceeds Daphnes.
© Stack Overflow or respective owner