java - 递归阶乘公式

标签 java recursion

我想获得显示类似 1*2*3*4 的输出,但我得到的是 4*3*2*1 这是我的代码:

public static int fact(int n)

    {
        if(n ==1)
            return 1;
        else
            return n * fact(n-1);
    }

    public static int factorForm(int n)
    {
        System.out.print(n);
        if (n == 1)
            return 1;
        else
        {
            System.out.print("*");
            return n + '*' + factorForm(n-1);
        }
    }

最佳答案

你正在调用 fact(4)

然后打印

然后调用 fact(3)

如果你反转你会得到你想要的:

public class fact { 
  static int f(int n)
  {
    if (n ==1 )
    {
        System.out.print(1);
        return 1;
    }
    int ret= (n * f(n-1));
    System.out.print("*");
    System.out.print(n);
    return ret;
  }

  public static void main(String[] args)
  {
    int ret=f(4);
    System.out.print("=");
    System.out.println(ret);
  }
}

关于java - 递归阶乘公式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20089798/

相关文章:

Java - 将字符串(4 个字符)转换为 int 并返回的乐趣

java - Gorm MongoDB 插件存储 jvm 对象 id 而不是字节数组数据

c - 使用递归反转单词

java - Mybatis SQL 中的递归导致编译时堆栈溢出

c++ - 递归反向字符串方法的参数过多错误

java - 在Java中查找特定文件夹

java - 我无法使用 findViewById 重新引用 TableRow

java - 如何更改 Tomcat 7 的服务器时区?

java - 如何绕过 "call to this must be first statement in constructor"?

c - 字符串的分配,两个字符串合二为一的递归函数