Determine the largest number among three numbers using C++

后端 未结 5 1388
暖寄归人
暖寄归人 2021-01-19 23:20

How can I determine the largest number among three numbers using C++?

I need to simplify this

 w=(z>((x>y)?x:y)?z:((x>y)?x:y));
相关标签:
5条回答
  • 2021-01-19 23:32

    Use the simple if condition

    int w = x;
    
    if(y > w)
      w = y;
    if(z > w)
      w = z;
    

    Where w is the max among three.

    0 讨论(0)
  • 2021-01-19 23:34

    big = a > b ? (a > c ? a : c) : (b > c ? b : c) ;

    0 讨论(0)
  • 2021-01-19 23:35

    A variant on oisyn's answer (use an initializer list) and Bathesheba's answer (invoke no copies) is to use std::ref to create an initializer list of references, and then use std::max normally:

    using std::ref;
    w = std::max({ref(x), ref(y), ref(z)});
    

    This is only advantageous if creating a reference is cheaper than creating a copy (and it isn't for primitives like int)

    Demo

    0 讨论(0)
  • 2021-01-19 23:46

    Starting from C++11, you can do

    w = std::max({ x, y, z });
    
    0 讨论(0)
  • 2021-01-19 23:55
    w = std::max(std::max(x, y), z);
    

    is one way.

    0 讨论(0)
提交回复
热议问题