Enhancing the Account Class

Last edited on
You didn't mention how often the interest is compounded annually. Some common values to assume would be one (once a year) or four (quarterly).

Here is a function that returns the final amount, given the principal (initial investment), the annual rate, the number of years and the number of times the interest is compounded annually (a default parameter set to 1).

1
2
3
4
5
6
7
8
9
double get_amount(double principal, double annual_rate, double number_years, double number_compounded = 1) {

	double annual_rate_decimal = annual_rate / 100.0;

	double amount = principal * ::pow((1.0 + (annual_rate_decimal / number_compounded)), (number_compounded * number_years));

	return amount;

}



However, this is different from what the assignment is asking. You'll need a function that returns the number of years it takes for an investment to double. Given the previous function, we know the relationship of these variables and can rewrite the equation to yield our desired value, and build a function around that:

1
2
3
4
5
6
7
8
9
10
double get_number_of_years_until_doubled(double principal, double annual_rate, double number_compounded = 1) {

	double annual_rate_decimal = annual_rate / 100.0;

	double multiplier = 2.0;

	double number_years = ::log10(multiplier) / (::log10(1.0 + (annual_rate_decimal / number_compounded)) * number_compounded);

	return number_years;
}

Topic archived. No new replies allowed.