Answer the question
In order to leave comments, you need to log in
If condition statement error in c++?
Hello, why, when using a range of values for a variable, does the condition statement admit any values for the variable?
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
int main() {
int hours, min;
cout << "Input hours: ";
cin >> hours;
cout << "Input min: ";
cin >> min;
if (9 <= hours <= 17 & 0 <= min <= 59) { //Проблема в этой строке
if (hours == 13 & min >= 30) {
cout << "Close";
}
else if (hours == 14 & min <= 30) {
cout << "Close";
}
else {
cout << "Open";
}
}
else {
cout << "Close";
}
system("pause>nul");
return 0;
}
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
int main() {
int hours, min;
cout << "Input hours: ";
cin >> hours;
cout << "Input min: ";
cin >> min;
if (hours >= 9 & hours <= 17 & min >= 0 & min <= 59) {
if (hours == 13 & min >= 30) {
cout << "Close";
}
else if (hours == 14 & min <= 30) {
cout << "Close";
}
else {
cout << "Open";
}
}
else {
cout << "Close";
}
system("pause>nul");
return 0;
}
Answer the question
In order to leave comments, you need to log in
if (9 <= hours <= 17 & 0 <= min <= 59)
Let me explain in detail why it doesn't work.
Let's say hours = 27 and min = 90, then
if (9 <= 27 <= 17 & 0 <= 90 <= 59) тогда
if (true <= 17 & true <= 59), тогда т.к. true = 1
if (1 <= 17 & 1 <= 59) тогда
if (true & true) => if (1 & 1)
в результате побитового сложения получаем if (1) => true => тело блока выполнится
if (9 <= 1 <= 17 & 0 <= -1 <= 59) тогда
if (false <= 17 & false <= 59) тогда
if (0 <= 17 & 0 <= 59) тогда
if (true & true) тогда
if (1 & 1)
if (1)
true
I guess it needs to be like this:
if ( (hours>=9 && hours <= 17) && (min >=0 && min <= 59) )
Because it should be &&
. &
is a bitwise AND, not a logical one.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question