gpt4 book ai didi

java - 无法获得此 "Factorial"程序的预期输出?

转载 作者:行者123 更新时间:2023-11-29 03:20:12 24 4
gpt4 key购买 nike

我叫 sam,我是 java 的初学者。我实际上已经自己尝试过这个“阶乘”程序,但我看不出逻辑出了什么问题……我没有得到预期的结果输出,谁能告诉我为什么?在此先感谢所有用户:)

阶乘:

import java.util.*;

class factorial {

public static void main(String[] args) {

int i;

System.out.println("enter a number");

Scanner in=new Scanner(System.in);

int n=in.nextInt();

int x=n;

while(x!=0) {
x=x*(n-1);
n--;
}

System.out.println(x);

}

}

当我输入(例如)5 时,我希望得到 5 (120) 的阶乘。相反,我得到零。所有输入都会发生这种情况。

最佳答案

如果你真的想学习,开始在脑海中逐行运行代码,例如:

int n = 5;

int x = n;
while (x != 0) {
x = x * (n - 1);
n--;
}

从一张纸开始:

  x  |  n
-----+-----
|
|
|
|

并且,当您“执行”每一行时,记下新值。这样做,您的问题所在就会立即显而易见。它还将使您成为更好的开发人员。

不要查看此答案的其余部分,直到您完成并尝试修复它。


一旦您理解了问题并(希望)解决了它,请将您拥有的内容与以下解决方案进行比较:

int n = 5;          // input value.

int x = 1; // initial accumulator set to identity (n * 1 = n).
while (n != 0) { // use all values from n down to 1 (inclusive).
x = x * n; // multiply accumulator by that value.
n--; // get next value.
}

关于java - 无法获得此 "Factorial"程序的预期输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24131842/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com