test me test me - 1 month ago 6
C++ Question

Why using ternary for a twice cause a probelm?

I have a program that checks if the a and b are in the range and if a is greater than b, then I want to add 5 to it but it will not add it, why ?

bool check(int a, int b){ // 1. check the range
return 1 <= a && a <= 100 && 1 <= b && b <= 100;
}
int main(){
int a0;
cin >> a0;
int b0;
cin >> b0;
int p = (check(a0, b0)) ? (a0 > b0) ? 1 : 0 : 0 + 5; // 2. after checking the range it will check whether a is greater than b
cout << p << endl;
return 0;
}

Answer

strange sequence ... but if both a & b are in the range [1,100] and a > b then p = a + 5 else p = a ????

int p = check(a0, b0) && a0 > b0 ? a0 + 5 : a0;
Comments