使用条件运算符在两个数字中找到最小的数字

时间:2012-01-25 09:43:43

标签: c conditional-operator

请给出详细的解释。 它是如何工作的?

3 个答案:

答案 0 :(得分:3)

return a<b ? a : b

相当于

if (a<b)
    return a;
else
    return b;

答案 1 :(得分:1)

条件运算符? :的工作方式与if else类似。

所以:

int A;
int B;
// some code that sets the values of A and B
return A>B?B:A

相同
int A;
int B; 
    // some code that sets the values of A and B   
if A>B
    return B;
else
    return A;

条件运算符的解释:

`<Perform operation that gives a boolean result>` ? <return this answer if true> : <return this answer if false>

所以你可以:

int smallestValue;
int inputA;
int inputB;

//some code that sets the value of inputA and inputB - perhaps from console input

smallestValue = (inputA < inputB) ? inputA : inputB;

答案 2 :(得分:0)

这是一个宏做同样的工作......

#define min(a, b) a<b ? a : b
相关问题