samedi 15 août 2020

C++ Separate "if" statements don't work but nested "if" statements do

I'm working through Programming Principles and Practice Using C++ and have run into an issue with multiple "if" statements within a while statement. In short, I run the following and the final "if" statement outputs each iteration regardless of input:

int main() {
    int i = 0;
    double a;
    double b;
    constexpr double ratio = (1.0/100);
    while (i<5) {
        cout << "Please enter two doubles\n"
             << "> ";
        cin >> a >> b;
        if (a > b) {
            cout << "The smaller value is " << b << " and the larger value is " << a << ".\n";
        }
        else if (a < b) {
            cout << "The smaller value is " << a << " and the larger value is " << b << ".\n";
        }
        else if (a == b) {
            cout << "The numbers are equal.\n";
        }

        if (((a-b) < ratio) || ((b-a) < ratio)) {
            cout << "Also, the numbers are almost equal.\n";
        }
        ++i;
    }
...

However, if I modify it to use nested "if" statements instead, it works as expected:

int main() {
    int i = 0;
    double a;
    double b;
    constexpr double ratio = (1.0/100);
    while (i<5) {
        cout << "Please enter two doubles\n"
             << "> ";
        cin >> a >> b;
        if (a > b) {
            cout << "The smaller value is " << b << " and the larger value is " << a << ".\n";
            if ((a - b) < ratio) {
                cout << "Also, the numbers are almost equal.\n";
            }
        }
        else if (a < b) {
            cout << "The smaller value is " << a << " and the larger value is " << b << ".\n";
            if ((b - a) < ratio) {
                cout << "Also, the numbers are almost equal.\n";
            }
        }
        else if (a == b) {
            cout << "The numbers are equal.\n";
        }
        ++i;
    }
...

What's going on here? I feel like perhaps I'm losing the inputs, but I can't figure out why...

Aucun commentaire:

Enregistrer un commentaire