【问题标题】:how can we get three numbers max in c++ using function我们如何使用函数在C ++中获得三个数字最大值
【发布时间】:2022-11-23 21:03:57
【问题描述】:

我们取三个数字,如 a、b 和 c。现在我们使用 function 来最大化这三个。

#include <iostream>
using namespace std;

int main()
{
  int x = 10, y = 20, z = 30;
  int num = max(x, y, z);
  cout << num;
}
int max(int a, int b, int c)
{
  int num = a;
  if (b > num)
  {
    num = b;
  }
  if (c > num)
  {
    num = c;
  }
  return num;
}

【问题讨论】:

标签: c++ function max


【解决方案1】:

您可以编写一个可以使用任意数量的参数调用的可变参数模板 max 函数。例子:

template <typename Head0, typename Head1, typename... Tail>
constexpr auto max(Head0 &&head0, Head1 &&head1, Tail &&... tail)
{
    if constexpr (sizeof...(tail) == 0) {
        return head0 > head1 ? head0 : head1;
    }
    else {
        return max(max(head0, head1), tail...);
    }
}

【讨论】:

    猜你喜欢
    • 2021-01-10
    • 2010-12-21
    • 2021-04-14
    • 2018-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-06
    相关资源
    最近更新 更多