Search code examples
c++while-loopconverterstemperature

Why doesn't this while loop show the first element?


I'm a beginner of C++ and wanted to do this exercise. The following is my code but I can't figure out why it doesn't show the lower limit when cout the while loop.

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    double low=-0.000001, high=-0.000001, step=0.0, stop, f;
    while (low <= -0.000001 || low > 50000) {
        cout << "Lower limit (0~50,000): "; cin >> low;
        if (low <= -0.000001) {cout << "Must be positive." << endl;}
        else if (low > 50000) {cout << "Out of range." << endl;}
    }
    while (high <= -0.000001 || high > 50000 || high <= low) {
        cout << "Higher limit (0~50,000): "; cin >> high;
        if (high <= -0.000001) {cout << "Must be positive." << endl;}
        else if (high > 50000) {cout << "Out of range." << endl;}
        else if (high <= low) {cout << "Must higher than lower limit." << endl;}
    }
    while (step <= 0 || step > high) {
        cout << "Step (0.000001~" << high << "): "; cin >> step;
        if (step <= 0) {cout << "Must be positive." << endl;}
        else if (step > high) {cout << "Out of range." << endl;}
    }
    cout << endl << "Celsius\t\tFahrenheit" << endl;
    cout << "-------\t\t----------" << endl;
    stop = low;
    while (stop < high) {
        f = 1.8 * stop + 32.0;
        stop += step;
        cout << fixed << setprecision(6) << stop << "\t" << fixed << setprecision(6) << f << endl;
    }
    return 0;
}

For example, if I enter 1.5 for lower limit, I imagine its output should start with 1.5 but instead it starts with 2.0... How can I fix this? Thanks.

Img of Not the outcome I want


Solution

  • The first time stop is being printed is after the first increment:

    while (stop < high) {
        f = 1.8 * stop + 32.0;
        stop += step;                              <- increment
        cout << ... << stop << ... << f << endl;   <- print
    }
    

    Move the printing above that and it should work fine.


    Side note: it's rather easy to find such problems with a debugger and repeated "step over" commands (with perhaps a few watches showing how your interesting values are changing over time). Following the program execution step-by-step can be enlightning.