-3

Problem:

I am practicing from my college's introduction problem set of creating a program where the user introduces four variables a, b, c, d and: if a is in (c; d) AND b isn't in (c; d) the program should print a, b and a+b; otherwise it should print a, b and a-b:

I noticed that if the user introduces a, b such that BOTH statements are false it prints a+b instead of a-b. Why does it happen?

Attempt:

#include<iostream>
using namespace std;

int main()
    {int a,b,c,d;
    cout<<"Introduza a: ";
    cin>>a;
    cout<<"Introduzca  b: ";
    cin>>b;
    cout<<"Introduzca c: ";
    cin>>c;
    cout<<"Introduzca d: ";
    cin>>d;
    if( (c<a<d) && ((b<c || d<b)))
        {cout<<"a= " <<a <<"\n";
        cout<<"b= " <<b << "\n";
        cout<<"a+b= " <<a+b <<"\n";
        }
    else
        {cout<<"a=" <<a <<"\n";
        cout<<"b= " <<b <<"\n";
        cout<<"a-b= " <<a-b <<"\n";}
        }       
Emma
  • 27,428
  • 11
  • 44
  • 69
Jose Rios
  • 1
  • 1

1 Answers1

2

in programming languages like C++, C, Java, PHP, .. something like (c<a<d) is spread out to (c < a && a < d). The second thing is that you do not need double parenthesizes here ((b<c || d<b)). This entire line:

if( (c<a<d) && ((b<c || d<b)))

should look like:

if (c < a && a < d && (b < c || d < b))

Hope this helps!!!!

CLARIFICATION PER COMMENT: What I mean in mathematics you write a < b < c in programming language you write this as a < b && b < c. In programming a < b < c is the same as (a < b) < c which in turns mean if a is less than b it will return 1 thus producing 1 < c. If a is greater or equal to b a < b will return 0 thus producing 0 < c.