Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- int checkPaymentAmount(float amount, float balance, float interest); //forward declaration of the function, nasty C necessity
- int main()
- {
- //declaration of the variables we'll be using
- float balance, lowerBound, upperBound, interest, midValue;
- int check;
- cin >> balance; //input of the balance
- cin >> interest; //input of the annual interest
- lowerBound = balance / 12; //given in the pdf
- upperBound = (balance + balance * interest) / 12; //given in the pdf (I think lol)
- bool inLoop = true; //we will use this boolean later to check if we have found the correct amount
- while (inLoop)
- {
- midValue = lowerBound + (upperBound - lowerBound) / 2; //we calculate the interval size, divide it by two and add that to the lowerBound, this will be our center value
- check = checkPaymentAmount(midValue, balance, interest);
- if (check == 0)
- inLoop = false;
- if (check == 1)
- lowerBound = midValue;
- if (check == -1)
- upperBound = midValue;
- }
- printf("%.2f", midValue); //this will print the answer with a precision of 2 decimals
- return 0;
- }
- //returns 1 if amount needs to be higher, -1 is it needs to be lower, 0 if it's acceptable
- int checkPaymentAmount(float amount, float balance, float interest)
- {
- float tempBalance = balance;
- //first we need to calculate the amount payed off with the original balance, to see if this will be sufficient
- for (int i = 0; i < 12; i++)
- {
- tempBalance = tempBalance * (1 + interest/12) - amount; //this is also used in the first problem I think
- }
- if (tempBalance > 0)
- return 1; //if you still have dept after paying this amount monthly, your amount was not high enough
- //this code below will only be executed if we've paid too much. We need to find out if we could've paid less and still pay off.
- //We will do this by checking if the amount - 0.01 gives us an amount in debt
- tempBalance = balance;
- amount = amount - 0.01;
- for (int i = 0; i < 12; i++)
- {
- tempBalance = tempBalance * (1 + interest/12) - amount;
- }
- if (tempBalance > 0)
- return 0; //We have a dept now, so our initial amount was the littlest amount possible and we need to stop the loop
- else
- return -1; //this value was too high, so we need to search lower values
- }
Advertisement
Add Comment
Please, Sign In to add comment