### 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.

 ``1234567891011121314151617181920212223242526272829303132`` ``````#include 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:
 ``1234567891011121314`` ``````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.