【问题标题】:Is a function using template for data type not supposed to return long long int?使用模板作为数据类型的函数是否不应该返回 long long int?
【发布时间】:2019-08-08 06:13:03
【问题描述】:

我是 C++ 新手,我编写了一个函数,它接受 a 和 b 作为输入,并返回 a 的 b 次幂。我为函数返回数据类型和数据类型使用模板。但它无法返回大数的正确结果。我尝试计算 pow(2,50) 并返回 0。

template <class numeric_type>
numeric_type pow(numeric_type a, int b) {
    numeric_type result = 1;
    for (int i = 0; i < b; i++) {
        result *= a;
        cout << result << i << endl;
    }
    return result;
}

在main里面:

long long int powered = pow(2, 50);
cout << powered;

【问题讨论】:

    标签: c++ templates


    【解决方案1】:

    是的,那行不通。 '2' 的数字类型是 int。对 long long int 使用 '2LL'。这不起作用的原因是因为 2^50 太大而无法存储在整数中(它是一个 32 位的数字,但您需要 51 位来存储 2^50)

    auto powered = pow(2LL, 50);

    【讨论】:

      【解决方案2】:

      模板参数是从传递的函数参数推导出来的(但不是返回类型);所以给定pow(2, 50);,numeric_type推导出为int。

      您可以明确指定numeric_type,

      auto powered = pow<long long int>(2, 50); // specify numeric_type as long long int explicitly
      

      或在2 上添加显式转换以使其成为long long int。

      auto powered = pow(static_cast<long long int>(2), 50); // numeric_type is deduced as long long int
      

      【讨论】:

      • @ArianHassani 然后我建议按此答案左侧的绿色勾号将您的问题标记为已解决。
      • 2LL 会比 static_cast&lt;long long int&gt;(2) 短。
      猜你喜欢
      • 2023-03-29
      • 2014-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多