vendredi 5 juin 2020

Why does switching the order of the if else statement result in an error?

Here is my code:

/* 
    Given a positive integer denoting n, do the following:
        - If 1 <= n <= 9, then print the lowercase English word corresponding to
        the number (e.g., one for 1, two for 2, etc.)
        - If n > 9, print 'Greater than 9'.
*/

#include <iostream>
#include <array>

using namespace std;

int main()
{
    string english_names [9] = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
    int n;
    cin >> n;
    if(n>9) {
        cout << "Greater than 9";
    }
    else {
        cout << english_names[n-1];
    }
}

Using the above code works perfectly, however if I change the if else statement to:

if(1<=n<=9) {
        cout << english_names[n-1];
    }
    else {
        cout << "Greater than 9";
    }

Then the program no longer works properly. It works for an integer n where 1 <= n <= 9 however if the integer is greater than 9 the program does not work.

Aucun commentaire:

Enregistrer un commentaire