In: Computer Science
Write a function howManyMonths(start, rate, spending, target) where:
start - the starting balance in your bank account (float)
rate - the monthly interest rate (float) - like 0.001 for 0.1%
spending - the monthly amount that is spent each month (float)
target - the target savings that you’d like to achieve
The function returns how many months it takes to save the target savings amount. The function should return a -1 if the balance goes below 0 because the spending is too high. The function should also return -1 if the target is not reached after 100 months.
Each month you earn the monthly rate of interest, but you also spend the spending amount.
So, next_month_balance = start_balance * (1 + rate) - spending
since the language is not mentioned c++ is use here
code in python
def  HowManyMonths(start,rate,spending,target):
    no_ofmonths=0
    while start<target:
        no_ofmonths=no_ofmonths+1
        if(no_ofmonths>=100):#checking months exceeded 100
            return -1
        start = start* (1 + rate) - spending
        if(start<0):#checking balance less than 0
            return -1
    return no_ofmonths
print(HowManyMonths(1000,.3,200,2000))
code in c++
#include <iostream>
using namespace std;
int HowManyMonths(float start,float rate,float spending,float target)
{
    int no_ofmonths=0;
    
    while(start<target)
        {    //cout<<start<<"  ";// change this to see updated start value after each iteration
            no_ofmonths=no_ofmonths+1;
            if(no_ofmonths>=100)//checking if no of months exceeds 100
            {
                return -1;
            }
            start = start * (1 + rate) - spending;
            if(start<0) //checking if balance if under 0
            {return-1;}
            
        }
        
        return no_ofmonths; 
        
    
}
int main()
{
    cout<<"\n"<<HowManyMonths(1000,.3,200,2000);
    return 0;
}
output
the output of the above code will be :
6