0

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;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
NickPG44
  • 11
  • 1

3 Answers3

3

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1
  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
robni
  • 904
  • 2
  • 6
  • 20
0

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?

digito_evo
  • 3,216
  • 2
  • 14
  • 42