Error in calculation

I created two while blocks, but only one of them works although I think they both should. I think I may have made syntax errors. I'm not really sure. Any help is appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>

using namespace std;

int main()
{
    double balance, payment, newb = 1;
	int month = 0;
	double rate =.10;			
	cout << "What is your balance? " << endl;
    cin >> balance;
    cout << "What is your payment? " << endl;
    cin >> payment;
	cout << endl;
	newb = balance;				//this while block seems to work
	while (newb > 0) {			// block 1
		balance-=payment;			
		balance *= rate;
		newb = newb + balance;
		month++;
	}
	/* while (balance > 0){			//block 2
		balance -= payment;				    // does not work
		balance = (balance + (balance * rate)); // should be the same as newb = newb * balance correct?
		month++;
	}*/
	
	
	cout << "It will take " << month << " months to pay off your balance." << endl;
	return 0;
	
}
Second loop works fine, but I would swap two first lines (first calculate interest, then accept payment). First does not works as intended: If I enter 1000 balance and 1 payment It will give me some answer. But I would never pay off my debt with such interest and monthly payment!
Second loop will just get into infinite loop.
I propose you to use second loop, but add check if balance at the end is larger than in the beginning like that:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
while (balance > 0) {
    old_balance = balance;
    balance -= payment;
    balance = (balance + (balance * rate));
    if(old_balance < balance) {
        month = 0;
        break;
    }
    month++;
}
if (month == 0)
    std::cout << "you will never pay off your debt";
else
    std::cout <<//... 

Or, better, check for possibility to payoff before loop, like: if ( balance < ((balance - payment) * (rate + 1)) )
Last edited on
MiiNiPaa made a good point in his last statement.

Implementing the if statement before loop as he described works even better. I compiled it in Xcode and it worked great.

I think it increases overall readability of the program from my standpoint. I would use that strategy depending on your intended purpose for creating this program.

Topic archived. No new replies allowed.