“在所有控制路径上递归”。实现阶乘函数时出错 [英] "Recursive on All Control Paths" error when implementing factorial function

查看:89
本文介绍了“在所有控制路径上递归”。实现阶乘函数时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于班级,我有一个作业:

For class I have an assignment:


编写一个C ++程序,该程序将输出选择 n 个对象( n 和<$ c中的> k 个对象$ c> k 应该是正整数)。此数字由以下公式给出:

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)!)

您的程序应使用两个返回值的函数。第一个应称为 factorial ,并应返回 n!。第二个函数应称为 combinations ,并应返回 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).

我想出了一个解决方案:

I came up with a solution:

#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; 
}

...但是我一直收到错误提示,

...but I keep getting an error, that says;


阶乘:在所有控制路径上递归,函数将导致运行时堆栈溢出;

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

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

If someone could help me, I've been working on this for about an hour and I'm stumped!

推荐答案

那里是递归函数定义的两个关键元素:

There are two critical elements to a recursive function definition:


  • 对自身的递归调用

  • a 终止条件

  • a recursive call to itself
  • a termination condition

您似乎缺少终止条件。 factorial()如何永远退出自我调用?

You appear to be missing the termination condition. How would factorial() quit calling itself forever?

这篇关于“在所有控制路径上递归”。实现阶乘函数时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆