My code is to determine weather a person is available by his/her age. 6<=age<=10 means qualified. But no matter what number is input, output always is true.
#include <iostream>
int main() {
std::cout << "What is your age?";
int age;
std::cin >> age;
you defined allowed twice, that is not allowed ;)
actually, it is, because they are local to the if and else blocks, but you don't want that.
try
bool allowed{}; //defaults to false here up towards the top of the code
if (!(6<=age<=10))
allowed = true;
///don't need an else, it was already false otherwise.
if(true)... this is always true. if what is true? if true is true!
should be
if(allowed)
also please use code tags, as code gets bigger and more complex, it is unreadable without.
#include <iostream>
int main() {
std::cout << "What is your age?";
int age {};
std::cin >> age;
constauto allowed {age >= 6 && age <= 10};
if (allowed)
std::cout << "\nYou can be enrolled.\n\n";
else
std::cout << "\nYou can't be enrolled. Go away.\n\n";
}
You don't need to use allowed:
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
int main() {
std::cout << "What is your age?";
int age {};
std::cin >> age;
if (age >= 6 && age <= 10)
std::cout << "\nYou can be enrolled.\n\n";
else
std::cout << "\nYou can't be enrolled. Go away.\n\n";
}
if ( 6 <= age <= 10 ) {
This doesn't do what you think it does. You need: if ( age >= 6 && age <= 10 ) {
The reason for this is that the <= is a binary operator that returns bool (true or false). Binary operator has two operands.
There are precedence and order of evaluation rules for expressions that more than one operator.
When you write 6 <= age <= 10, it is like you had written (6 <= age) <= 10.
The (6 <= age) is evaluated first and the result is true or false.
Therefore, depending on result of 6 <= age, the 6 <= age <= 10
actually progresses to true <= 10 or false <= 10.
That is not what you want.
The relations <=, >= have higher precedence than boolean AND &&.
Therefore, the age >= 6 && age <= 10 is like (age >= 6) && (age <= 10)
Both relations are evaluated first, and if both are true, then the whole expression is true.
There is one ternary operator. The ? : takes three operands: A ? B : C
If A is true, then return B, else return C.