简体   繁体   English

Java 阶乘程序

[英]Java Factorial Program

I can't figure out what I'm missing on my code.我无法弄清楚我的代码缺少什么。 Any help will be greatly appreciated.任何帮助将不胜感激。 I'm new in coding and I'm just doing some practice.我是编码新手,我只是在做一些练习。 Thank you!谢谢!

import java.util.Scanner;
import java.lang.Math;

public class Factorial {

    public static Scanner sc;

    public Factorial() {
    }

    int factorial(int n) {
        for (int j = n - 1; j > 0; j--) {
            int factorial = factorial(0) * j;
        }
        return factorial(0);
    }

    public static void main(String[] args) {

        System.out.print("Enter a number to find its factorial: ");
        sc = new Scanner(System.in);
        int myNumber = sc.nextInt();

        Factorial myFactorial = new Factorial();
        System.out.println(myFactorial.factorial(myNumber));
    }
}

You're missing the corner case (for 0):你错过了角落案例(0):

int factorial(int n) {
    if (n == 0) return 1;
    for (int j = n - 1; j > 0; j--) {
        int factorial = factorial(0) * j;
    }
    return factorial(0);
}

In recursive mode : `在递归模式下:`

import java.util.Scanner;
import java.lang.Math;




class Factorial {

public static Scanner sc;


public static int factorial(int n) {
    if(n==0)return 1;
    return n*factorial(n-1);
}

public static void main(String[] args) {

    System.out.print("Enter a number to find its factorial: ");
    sc = new Scanner(System.in);
    int myNumber = sc.nextInt();

    //Factorial myFactorial = new Factorial();
    System.out.println(factorial(myNumber));
}
}`

Well.... regardless of what you provide on n, you always return factorial(0) which ends up creating an endless loop of calls to factorial so I guess your stack is getting hammered and getting an Stack Overflow error, right?嗯.... 不管你在 n 上提供什么,你总是返回factorial(0) ,这最终会创建一个对factorial的无限循环,所以我猜你的堆栈正在受到冲击并出现堆栈溢出错误,对吧? I think that's where the error is.我认为这就是错误所在。

For every recursive function, you must need to write a base case else it will end up doing recursion and at the end it will cause stack overflow error(not the name of this site, it is an error), which is what you are missing right there in your algorithm.对于每个递归函数,您必须编写一个基本情况,否则它最终会进行递归并最终导致堆栈溢出错误(不是该站点的名称,这是一个错误),这就是您所缺少的就在你的算法中。

For finding factorial recursively递归求阶乘

Mathematically数学上

n!啊! = nx (n - 1)! = nx (n - 1)! and the base case is 0!基本情况是0! = 1 = 1

In Java在 Java 中

// somewhere in your class
int factorial(int n) {
   // base case
   if (n == 0) return 1;

   // recursion
   return n * factorial(n-1);
}

Replace this code in your code:在您的代码中替换此代码:

 int factorial=1;
int factorial(int n) {
   for (int j = 1; j <= n; j++) {
       factorial = factorial * j;
    }
    return factorial;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM