Home > Enterprise >  Why does it display the sum if numbers aren't between the 2 values?
Why does it display the sum if numbers aren't between the 2 values?

Time:01-10

I want it to not display the result of the sum if the numbers are lower or equal to 1 or 1000. I don't know if using if is the best way, but that's what I tried using, and I don't really understand why it doesn't work. I also tried writing conditions with || and &&, but those don't work either.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
    
int sum;
int a, b, c;

int main() {
     
    cin >> a;
    cin >> b;
    cin >> c;
    
    sum = a   b   c;
        
    if ( 1 <= a, b, c <= 1000) {  //also tried ( 1 <= a || b || c <= 100) and ( a, b, c >= 1 && a, b, c <= 1000)
        cout<< sum;
    }
    else {
        cout<< "can't calculate"; 
    }
    
    return 0;
}

CodePudding user response:

The expression in this if statement

if ( 1 <= a, b, c <= 1000)

is an expression with the comma operator. It is equivalent to

if ( ( 1 <= a ), ( b ), ( c <= 1000 ) )

and the value of the expression is the value of its last operand. That is this if statement is equivalent to

if ( ( c <= 1000 ) )

It seems you mean

if ( 1 <= a && a <= 1000 && 1 <= b && b <= 1000 && 1 <= c && c <= 1000 )
{
    std::cout << a   b   c << '\n';
}

Pay attention to that there is no sense to calculate the sum

sum = a   b   c;

before the checking the values of the variables a, b and c in the if statement.

CodePudding user response:

  1. Why do you have so much includes? Your code just need iostream. Anything else could be removed.
  2. Your if-condition doesn't have the right syntax. You can't write "a and b and c should be under 1000", you must do it for every var. Try:
a >= 1 && a <= 1000 &&
b >= 1 && b <= 1000 &&
c >= 1 && c <= 1000

CodePudding user response:

You probably want this:

if ( a >= 1 && b >= 1 && c >= 1 &&
     a <= 1000 && b <= 1000 && c <= 1000 )
{
    std::cout << a   b   c;
}

Your code is not correct. You have to use the correct syntax.

Note: see Why is "using namespace std;" considered bad practice?

  •  Tags:  
  • Related