gpt4 book ai didi

c++ - "Recursive on All Control Paths"执行阶乘函数时出错

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:56:18 24 4
gpt4 key购买 nike

对于类我有一个作业:

Write a C++ program that will output the number of distinct ways in which you can pick k objects out of a set of n objects (both n and k should be positive integers). This number is given by the following formula:

C(n, k) = n!/(k! * (n - k)!)

Your program should use two value-returning functions. The first one should be called factorial and should return n!. The second function should be called combinations and should return n!/(k! * (n - k)!). Test your program for different values of n and k five times (count-controlled loop).

我想到了一个解决方案:

#include <iostream>
using namespace std;
int factorial(int);
int combination(int, int);

void main(void)
{
int objects, set_number, count;
count = 1;
while(count <= 5)
{
cout << "Please enter in number of objects ";
cin >> objects;
cout << "Please enter in the number of Sets ";
cin >> set_number;
count++;
}

cout << "The Factorial is " << factorial(set_number) << " & the combination is " << combination << endl;
cout << endl;
}

// Factorial
int factorial(int set_number)
{
int cal;
cal = set_number * factorial(set_number - 1);
return cal;
}

// Combination
int combination(int objects, int set_number)
{
int com_total, cal_set, cal_obj, min_sum, cal_min;

cal_set = set_number * factorial(set_number - 1);
cal_obj = objects * factorial(objects - 1);

//n!/(k! * (n - k)!)
min_sum = set_number - objects;
cal_min = min_sum * factorial(min_sum- 1);
com_total = cal_set / (cal_obj * cal_min);
return com_total;
}

...但我一直收到错误消息;

"'factorial' : recursive on all control paths, function will cause runtime stack overflow;"

如果有人能帮助我,我已经为此工作了大约一个小时,但我很困惑!

最佳答案

递归函数定义有两个关键元素:

  • 对自身的递归调用
  • 终止条件

您似乎缺少终止条件。 factorial() 将如何永远停止调用自身?

关于c++ - "Recursive on All Control Paths"执行阶乘函数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3937007/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com