What do you do when you have a problem using 'if' option after generating a random number?

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>

int main()
{
  int a;
  scanf("%d", &a);
  srand(time(NULL));
  int random1 = rand() % ((90-0)+1)+0;
    printf("%d\n", random1);
    if (0<=a<=17)
    printf("good\n");
    else
    printf("bad\n");
return 0;
}

This only prints ‘good’ when ‘a’ isnt in range.

This actually always prints “good”, and it has nothing to do with the random number. The reason is that you combine expressions in the if condition:

I’ll add parentheses to show what actually happens here:

if ((0 <= a) <= 17)

The result of 0 <= a is always either 0 (false) or 1 (true). And both 0 and 1 are less than or equal to 17. :slightly_smiling_face:

If you want to make sure that a is in the range from 0 to 17 (inclusive) you need to check both conditions separately and combine them with a && (logical and) operator.

I understand! thanks

1 Like