-4
#include <stdio.h>
int main () {
  float x = 30;
  if (x < 9) {
    printf("A");  
  } else if (10 <= x <= 20) {
    printf("B"); 
  } else if (21 <= x <= 29.9) {
    printf("C");
  } else {
    printf("Hello");
  }
  return 0;
}

My expected output is "Hello" since the value of x is 30 and it does not satisfy in any condition. However, the program's output is "B". I cannot figure out why.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Jakeyyyy
  • 1
  • 5

2 Answers2

2

The condition

else if (10 <= x <= 20)

is wrong, the compiler throw indeed a warning:

warning: result of comparison of constant 20 with boolean expression is always true

The correct way to do this control is to break the expression into two condition in logical and:

else if (10 <= x && x <= 20)
th3g3ntl3man
  • 1,926
  • 5
  • 29
  • 50
  • Owww! It worked. I thought that expression will work in C. (For context, my first language is Python and I am currently learning C.) Thank you for this! – Jakeyyyy Feb 24 '22 at 13:38
  • Just another question. Does "else if (10 <= x <= 20)" is valid in Python but not in C? – Jakeyyyy Feb 24 '22 at 13:39
  • If I not wrong, in python is possible to write the condition as you said but C is a low level programming language so you need to break the expression – th3g3ntl3man Feb 24 '22 at 13:43
0

In the second condition, try adding &&. For example, else if(10 <= x && x <= 20)

Candy
  • 53
  • 9
  • 1
    Stack Overflow is a site intended to be a durable repository of useful information in the form of questions and answers. It is not intended to be a free coding or debugging service. Answers should **explain** why code works in a particular way and give information about what was wrong with original code and why alternate code works. Answers that just tell people to change their code, without explaining why, are not good answers. – Eric Postpischil Feb 24 '22 at 14:11