简体   繁体   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

I am new to programming and I am trying to figure out how to get a java program to correctly run a factorial and ask the user if they would like to continue and input another number to use and display the factorial for that one. 我是编程新手,我试图弄清楚如何使Java程序正确运行阶乘并询问用户是否要继续并输入另一个数字以使用该阶乘并显示该阶乘。 When the user inputs "y", the program is supposed to then ask for another number. 当用户输入“ y”时,程序应询问另一个数字。 If they select "n", the program should terminate. 如果他们选择“ n”,则程序应终止。 I've been working on this code for a day and still haven't figured out where I am going wrong in the code to make it solve factorials correctly while looping. 我已经花了一天的时间来编写此代码,但仍然没有弄清楚我在代码中出了什么问题,以使其在循环时能正确解决阶乘。 Can someone please help me? 有人可以帮帮我吗?

  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."); } } 

Okay, first, you need to know what a factorial is. 好吧,首先,您需要知道什么是阶乘。

n! n! = n * (n-1)! = n *(n-1)!

That's important to understand. 了解这一点很重要。 The factorial if 5 is 5 times the factorial of 4. That's actually kind of cool and very useful. 5阶乘是4阶乘的5倍。这实际上很酷,而且非常有用。 So you can write a function that does that. 因此,您可以编写执行此操作的函数。

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

So what you do is define a method similar to the above. 因此,您要做的是定义与上述类似的方法。 And then in your loop where you ask them to enter a number, you call this method. 然后在要求他们输入数字的循环中,调用此方法。 It calls itself as needed to do the calculation for you. 它会根据需要自行调用以进行计算。

There are other ways. 还有其他方法。 You can do a for-loop. 您可以进行for循环。

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

But the recursive method is kind of cool. 但是递归方法有点酷。

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

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