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

查看:137
本文介绍了递归使用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>\n");
                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\n", rv);
        return 0;
}

程序编译使用 GCC 但执行力,我正在逐渐分段错误** P = N 。有人可以帮我修改上面的程序,以获得正确的结果。此外,什么是捕捉连续的递归调用之间的正确 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.

编写这样code为乐趣是确定的,但千万不要让不良行为遵循了严重的编码项目或工作场所。

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>\n");
                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\n", rv);

        return rv;
}

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

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