A
A
avion2018-09-19 15:37:55
C++ / C#
avion, 2018-09-19 15:37:55

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;
}

But in such cases, everything is fine?
#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

3 answer(s)
J
JaxxDexx, 2018-09-19
@avion123678

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 => тело блока выполнится

Second example
Let hours = 1 and min = -1, then
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

Those. no matter what values ​​you substitute, the block will always be executed

L
laphroaig, 2018-09-19
@laphroaig

I guess it needs to be like this:

if (  (hours>=9 && hours <= 17) && (min >=0 && min <= 59) )

A
Alexey Ukolov, 2018-09-19
@alexey-m-ukolov

Because it should be &&.
&is a bitwise AND, not a logical one.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question