Reputation: 13
Hey so I recently started learning C++ and I can't figure out why this problem is giving a false positive all the time.
Maybe someone can help?
// [Included stuff]
using namespace std;
int main() {
int erg = 5;
int inp;
cout << "Answer: 3 + 2: ";
cin >> inp;
if (inp == erg) {
cout << "True!";
};
if (inp <= erg || inp >= erg) {
cout << "False!";
}
else {
};
}
Upvotes: 1
Views: 332
Reputation: 11
if (inp <= erg || inp >= erg)
means less than or equal to or greater than or equal to so in effect it always evaluates to true. Use only < (less than) and/or > greater than or use not equal ( != ) instead so code would be
if (inp < erg || inp > erg)
or even simpler
if (inp != erg )
Upvotes: 1
Reputation: 310980
The condition in this if statement
if (inp <= erg || inp >= erg) {
cout << "False!";
}
means that inp can be equal to any number. That is the condition is always evaluates to true so the enclosed statement
cout << "False!";
is outputted.
It seems you mean either
if (inp != erg) {
cout << "False!";
}
or (that is only confusing because too complicated)
if (inp < erg || inp > erg) {
cout << "False!";
}
Or you could write something like
if (inp == erg) {
cout << "True!\n";
}
else if ( inp < erg ) {
cout << "False! Less than the result\n";
}
else {
cout << "False! Greater than the result\n";
}
If you have a condition like this
inp == erg
then its negation will look like
!( inp == erg )
or more readable
not ( inp == erg )
that is the same as
inp != erg
It would be enough to write
if (inp == erg) {
cout << "True!\n";
}
else {
cout << "False!\n";
}
Pay attention to that semicolons after closing braces are redundant.
Upvotes: 1
Reputation: 489
The term
if (inp <= erg || inp >= erg) {
cout << "False!";
}
is always true. The term inp <= erg
is true for each value of inp
in range of [-infinite,erg]
. The term inp >= erg
is true for each value of inp
in range of [erg,infinite]
. So the tem inp <= erg || inp >= erg
is true for each value of inp
in range of [-infinite,infinite]
.
Wish you much fun coding in C++.
Upvotes: 0