Kaleab_Asfaw's blog

By Kaleab_Asfaw, history, 4 years ago, In English

I am a beginner in c++, I am trying to write a program that read 7 integers like x, a, b, c, d, e, f.

The program is to count how many of the following condition are true:

x is in [a, b]

x is in [c, d]

x is in [e, f]

so the program will return either 1, 2, 3. my program :

Code:

I used to variable a and b to get input for the three pair intervals.

sample input : 7 1 10 5 6 4 40

expected output: 2

The program final result will give 2, but when I uncomment line 12 (print the value of the a and b before increment cnt ) the final result will be 3.

I don't know why I am getting different result. Does printing have effect of the code below?

I haven't seen this kind of thing in Python3 (know well). This question might seem silly for you but I am very confused why this is happening?

Thanks in Advance!

  • Vote: I like it
  • -1
  • Vote: I do not like it

»
4 years ago, # |
  Vote: I like it +12 Vote: I do not like it

Using curly braces {} for the if on line 11 should solve your problem. An if must be followed by curly braces if you want more than one statement to be executed when it is true. When you uncomment line 12, only the cout is conditional on the if, the counter is incremented each time irrespective of the bool value of the if condition. When line 12 is commented the if is binding on the next uncommented statement(++cnt;) and only on it.

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Compile with g++ -Wmisleading-indentation <PROGRAM>.

       -Wmisleading-indentation (C and C++ only)
           Warn when the indentation of the code does not reflect the block
           structure.  Specifically, a warning is issued for "if", "else",
           "while", and "for" clauses with a guarded statement that does not
           use braces, followed by an unguarded statement with the same
           indentation.

           In the following example, the call to "bar" is misleadingly
           indented as if it were guarded by the "if" conditional.

                     if (some_condition ())
                       foo ();
                       bar ();  /* Gotcha: this is not guarded by the "if".  */

           This warning is enabled by -Wall in C and C++.