i have a task in c . I have to write program checks whether a number is between 10 and 50. I wrote something but it errors, can you help me please.
#include <iostream>
using namespace std;
int main()
{
int a;
cout << "enter number";
cin >> a;
if ( 10 < a < 50)
cout << "True";
else
cout << "False";
return 0;
}
CodePudding user response:
The expression 10 < a < 50
is actually the same as (10 < a) < 50
.
So it compares the boolean true or false result of 10 < a
with the integer value 50
.
The comparison will always be true, since 10 < a
will be either 0
or 1
when converted from false
or true
, respectively.
You need to make two separate comparisons, chained together with the logic AND operator &&
, like 10 < a && a < 50
.
CodePudding user response:
You can't write if statements like a < b < c
. You can compare only two things at the moment, so, you have to change your if statement like that
if (a > 10 && a < 50){
// correct
} else {
// not correct
}
In C , &&
is a logic AND, while ||
is a logic OR. Now, this statement means "if a is more than 10 AND a is fewer than 50.
Update
Actually, you can compare a < b < c
, but this will lead to behavior that you probably are not expecting. Instead of that, will be better to use logic AND and logic OR to separate such a comparements into several, much simple comparements like a < b AND b < c
.