使用 main() 函数进行递归 [英] Recursion using main() function

查看:14
本文介绍了使用 main() 函数进行递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序来使用 main() 函数的递归计算阶乘.

I am writing a program to calculate factorial using recursion of main() function.

/* Print factorial */
#include <stdio.h>
#include <stdlib.h>

static char **p;

int main(int argc, char **argv)
{
        int n, rv;
        if (argc < 2) {
                printf("Usage: a.out <value>
");
                exit(-1);
        }
        n = atoi(argv[1]);
        if (!n) {
                rv = 0;
        } else {
                if (n == 1) {
                        rv = 1;
                } else {
                        n = n - 1;
                        **p = n;
                        main(2, p);
                }
        }
        printf("%d
", rv);
        return 0;
}

程序使用 gcc 编译,但在执行时,我在 **p = n 处遇到分段错误.有人可以帮我修改上述程序以获得正确的结果.另外,在 main() 中的连续递归调用之间捕获正确的 rv 值的逻辑是什么?

The program compiles using gcc but on execution, I am getting a Segmentation Fault at **p = n. Can somebody help me to modify the above program to get the correct result. Also, what is the logic to capture correct rv value between successive recursive calls in main()?

推荐答案

由于你似乎并不关心标准和东西,这里是打印阶乘的递归主函数的实现,它在 gcc 上编译(我只在 Windows 上测试).由于它不遵循标准,因此不能保证它会在其他编译器/平台上编译.

Since you don't seem to care about standard and stuffs, here is an implementation of the recursive main function for printing factorial, that compiles on gcc (I only test on Windows). Since it doesn't follow standard, there is no guarantee that it will compiles on other compiler/platform.

为了好玩而编写这样的代码是可以的,但永远不要让不良行为进入严肃的编码项目或工作场所.

Writing such code for fun is OK, but never let the bad behavior follows into serious coding project or workplace.

/* Print factorial */
#include <stdio.h>
#include <stdlib.h>

char buf[16];

int main(int argc, char **argv)
{
        int n, rv;

        if (argc < 2) {
                printf("Usage: a.out <value>
");
                exit(-1);
        }

        n = atoi(argv[1]);
        if (!n) {
                rv = 1;
        } else {
                if (n == 1) {
                    rv = 1;
                } else {
                    char *pt = buf;
                    char **pt2 = &pt - 1;

                    sprintf(buf, "%d", n - 1);
                    rv = main(2, pt2) * n;
                }
        }
        printf("%d
", rv);

        return rv;
}

这篇关于使用 main() 函数进行递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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