在 C++ 中的数组上使用阶乘函数

Using a Factorial Function on an Array in C++

本文关键字:阶乘 函数 数组 C++      更新时间:2023-10-16

我试图让我的阶乘函数遍历数组中的所有数字并给我结果,但我不断收到错误消息。知道我做错了什么吗?这是我的代码:

#include <iostream>
#include "Recursion.h"
int factorial(int n)
{
if (n == 0)
return 1;
else
return n * factorial(n-1);
}
int main()
{
int my_list[5] = {2, 4, 6, 8, 10};
for(int i = 0; i < 5; ++i)
{
int b = factorial(my_list[i]);
std::cout << b << std::endl;
}
return 0;
}

您的函数设计为采用单个整数,而不是数组。遍历数组,并对数组中的每个 int 调用该方法

for(int i = 0; i < 5; ++i)
{
int b = factorial(my_list[i]);
std::cout << b << std::endl;
}