Conditional Release Problem in C ++

Here is the question I was trying to solve:

You are given a positive integer, n,:

If 1 ≤ n ≤ 9, print his English submission. This is “ one ” for 1, “ two ” for 2, etc.

Otherwise, type " Greater than 9 " (without quotes)

Here is part of my suggested answer, but it does not work!

int n;

if (1 <= n <= 9) {
    if (n == 1) {
    cout << "one" << endl;
    } else if (n == 2) {
    cout << "two" << endl;
    } else if (n == 3) {
    cout << "three" << endl;
    } else if (n == 4) {
    cout << "four" << endl;
    } else if (n == 5) {
    cout << "five" << endl;
    } else if (n == 6) {
    cout << "six" << endl;
    } else if (n == 7) {
    cout << "seven" << endl;
    } else if (n == 8) {
    cout << "eight" << endl;
    } else if (n == 9) {
    cout << "nine" << endl;
    }
} else {

    cout << "Greater than 9" << endl;
}

What is the problem with the code?

+4
source share
3 answers

Change if (1 <= n <= 9)toif (n>= 1 && n<=9)

+7
source

if (1 <= n <= 9) , . ((1 <= n) <= 9). <= , , "true" "false" 9.

'and' & &.

+5

if (1 <= n <= 9) { it should be if (1 <= n && n <= 9) {

You can also come to a solution using the instructions switch:

//Problem states n is a positive integer, so no need to check if n < 1
switch(n)
{
  case 1: cout << "one" << endl; break;
  case 2: cout << "two" << endl; break;
  //etc...
  case 9: cout << "nine" << endl; break;
  default: cout << "Greater than 9" << endl;
}

It does the same, but in my opinion it looks cleaner.

+1
source

Source: https://habr.com/ru/post/1627379/


All Articles