繁体   English   中英

如果用户输入“ y”并且阶乘部分也正常运行,则获取带有while循环的Java阶乘程序以保持重复

[英]Getting a Java factorial program with a while loop to keep repeating if the user enters with “y” and has the factorial part working as well

我是编程新手,我试图弄清楚如何使Java程序正确运行阶乘并询问用户是否要继续并输入另一个数字以使用该阶乘并显示该阶乘。 当用户输入“ y”时,程序应询问另一个数字。 如果他们选择“ n”,则程序应终止。 我已经花了一天的时间来编写此代码,但仍然没有弄清楚我在代码中出了什么问题,以使其在循环时能正确解决阶乘。 有人可以帮帮我吗?

  int i = 0; int factorial = 1; int input; char ind = 'y'; while (ind == 'y') { System.out.println("Please enter in a number to determine it's factorial: "); input = scan.nextInt(); scan.nextLine(); if ( i<= input) { i=input; i++; factorial = factorial * i; System.out.println(" the factorial of: " + input + " is " + factorial); }System.out.println(" Do you want to continue? (y/n) :"); ind = scan.nextLine().charAt(0); } System.out.println("goodbye."); } } 

好吧,首先,您需要知道什么是阶乘。

n! = n *(n-1)!

了解这一点很重要。 5阶乘是4阶乘的5倍。这实际上很酷,而且非常有用。 因此,您可以编写执行此操作的函数。

long factorial(long n) {
    if (n == 1) {
        return 1;
    }
    return n * factorial(n-1);
}

因此,您要做的是定义与上述类似的方法。 然后在要求他们输入数字的循环中,调用此方法。 它会根据需要自行调用以进行计算。

还有其他方法。 您可以进行for循环。

long result = 0;
for (long val = 2; val <= n; ++val) {
    result = result * val;
}

但是递归方法有点酷。

暂无
暂无

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

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