Reputation: 21
I am having a hard time figuring out what's wrong with my code. Here is my code and when i run it it displays the same word all over again even though i entered different numbers. Please help me, thanks a lot.
int main()
{
const int size = 4;
double arr[size];
int i;
cout << "Input numbers: ";
for(i=0;i<4;i++)
{
cin >> arr[i];
}
for(i=0;i<size;i++)
{
if(0<=arr[i]<=5)
{
cout << "HEY" << endl;
}
else if(0>arr[i])
{
cout << "Hello" << endl;
}
else if(10<arr[i]<20)
{
cout << "Haha" << endl;
}
else
{
cout << "Hoho";
}
}
cin.ignore(); cin.ignore();
return 0;
}
Upvotes: 0
Views: 149
Reputation: 11216
It's not only the range that's wrong (as others pointed out). With
else if(0>arr[i])
{
cout << "Hello" << endl;
}
else if(10<arr[i]<20)
{
cout << "Haha" << endl;
}
else
{
cout << "Hoho";
}
only the first else if
("Hello") will be executed for positive arr[i]. It catches all numbers greater than 5.
Upvotes: 0
Reputation: 22841
This if(0<=arr[i]<=5)
should be written as:
if( arr[i] >= 0 && arr[i] <= 5 )
This else if(10<arr[i]<20)
as
else if( 10 < arr[i] && arr[i] < 20 )
When you want logical anding
of conditions, i.e., you want both conditions to be true you should use the &&
operator. If the first test fails the other does not need to be evaluated:
From msdn link given above:
The conditional-AND operator (&&) performs a logical-AND of its bool operands, but only evaluates its second operand if necessary.
Upvotes: 1