Comparing two integers without any comparison

前端 未结 14 1816
温柔的废话
温柔的废话 2020-12-05 16:06

Is it possible to find the greatest of two integers without any comparison? I found some solutions:

if(!(a/b)) // if a is less than b then division result          


        
14条回答
  •  心在旅途
    2020-12-05 16:46

    Not one of the samples presented in the question or any of the answers thus far protects from division by zero. Why on earth are you trying to avoid an 'if' statement? I suspect homework question about ?: operators.

    cout << "Maximum is: " << ((a>b)?a:b)
    

    There we go.

    It's not possible to compare two numbers without a comparison. You can fudge it and do an indirect operation, but at the end of the day you're comparing something. Trust the compiler to optimize the code and select the best operations.

提交回复
热议问题