java factorial_Java Factorial Program

这篇博客讨论了一个新手程序员遇到的编程挑战,他们在实现阶乘计算的Java代码时遇到了无限递归的问题。问题在于缺少了基本情况的处理,导致函数不断调用自身。文章提供了多个修正方案,包括添加基线条件(如当n等于0时返回1)和使用非递归方法。修复后的代码避免了栈溢出错误,确保了正确计算阶乘。
摘要由CSDN通过智能技术生成

可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:

问题:

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

}

}

回答1:

You're missing the corner case (for 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);

}

回答2:

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

}

}`

回答3:

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! = n x (n - 1)! and the base case is 0! = 1

In Java

// somewhere in your class

int factorial(int n) {

// base case

if (n == 0) return 1;

// recursion

return n * factorial(n-1);

}

回答4:

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? I think that's where the error is.

回答5:

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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值