如何使用 std::accumulate() 获取数字的阶乘?

问题描述 投票:0回答:1

你好! 我使用函数

std::accumulate()
来查看对从 1 到 10 的自然数序列应用乘法运算时是否会返回 10 的阶乘,如下所示:

#include <iostream>
#include <numeric>
#include <functional>
using namespace std;

int main()
{
    int numbers[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    cout << "The factorial of 10 is " << accumulate(numbers + 1, numbers + 11,   multiplies<int>()) << "\n";"
}

现在我收到了奇怪的错误,指出函数

std::accumulate()
不是有效的操作数以及其他(我不记得这些错误)。

当我写这个问题时,我尝试再次运行代码,突然,错误消失了,一切顺利?

有人可以解释这种奇怪的行为吗?

c++ compiler-errors g++ accumulate
1个回答
0
投票

您错过了初始值参数:

#include <array>
#include <iostream>
#include <numeric>

int main()
{
    auto numbers = std::array{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    std::cout << "The factorial of 10 is "
              << accumulate(numbers.begin(), numbers.end(),  1,  std::multiplies<int>{})
        //                                                  🔺🔺🔺
              << '\n';
}

请注意,对于此计算,

int
是一个糟糕的算术类型选择,因为结果将大于 32767,而这正是
INT_MAX
所保证的。

© www.soinside.com 2019 - 2024. All rights reserved.