starrynights89
starrynights89

Reputation: 139

Getting while loop to display

#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

int main()
{
    int principal = 1000;
    int years = 1; //counter
    double balance = 0.0;
    double rate = .02; 

    do
    {
        cout << "Year " << years << ":" << endl;

        while (rate < .05)
        {
            balance = principal * pow(1 + rate, years); //display rate with no decimal place
            cout << fixed << setprecision(0);
            cout << "   Rate" << rate * 100 << "%: $";
            cout << setprecision(2) << balance << endl; //display balance with two decimal places
            rate += .01;
        }
        years += 1;
    } while (years < 6);

    system("pause");
    return 0;
}

I have this program that calculates the annual interest rate by 2%, 3%, and 4% and displays the amount for over 5 years. My while loop will run the first year and display it, but not years 2 through 5. I've edited the program several times over but I can't seem to get it to display the results. Any help with this would be appreciated.

Upvotes: 0

Views: 76

Answers (1)

iksemyonov
iksemyonov

Reputation: 4196

do
{
    cout << "Year " << years << ":" << endl;
    double rate = .02;
    ^^^^^^^^^^^^^^^^^^
    while (rate < .05)
    // rest of the code...

You forget to reset rater back to .02 every time the outer loop runs. Thus, the outer loop does get executed as it should, but since the inner loop does nothing due to the above error, you get no output.

Also, it is not really a good idea to compare double or float values in order to make decisions in loops or conditionals. Since floating-point arithmetic is not perfectly accurate in a computer due to its internal representation, your condition may evaluate to the opposite of what you expect it to be. Better redo the code in such a way that only integer or boolean types are compared, and perform the floating-point calculations elsewhere.

This is about how I'd do it (includes the fix by @vsoftco which I had no idea about! hope you don't me including it here for the sake of completeness and correctness). for loops make this neater:

#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

int main(int argc, char **argv)
{
    const int principal = 1000;
    double balance = 0.0;

    for (int years = 1; years < 6; ++years)
    {
        cout << "Year " << years << ":" << endl;
        for (int ratePercent = 2; ratePercent < 5; ++ratePercent)
        {
            double rate = ratePercent / 100.0;
            balance = principal * pow(1 + rate, years);
            cout << fixed << setprecision(0);
            cout << "   Rate" << ratePercent << "%: $";
            cout << setprecision(2) << balance << endl;
        }
    }

    cin.get(); // <--- per vsoftco comment!
    return 0;
}

Upvotes: 1

Related Questions