我应该创建一个程序,向用户询问一个数字,并接受该数字的阶乘,然后询问他们是否要执行另一个阶乘(Y,N)。
它应该像这样工作:
我的输出是这样的:
这是我的代码:
import java.util.Scanner;
public class factorial
{
public static void main ( String [] args )
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number you want to take the factorial of: ");
int num = input.nextInt();
int fact = 1;
System.out.printf("%d! = %d\n ", num, fact, Factorial(num, fact));
}
public static int Factorial(int num, int fact)
{
Scanner input = new Scanner(System.in);
char foo;
System.out.print("Do another factorial (Y,N)?");
foo = input.next().charAt(0);
for (int i = 1; i >= num; i++)
{
fact *= i;
if (foo == 'Y')
{
System.out.print("Do another factorial (Y,N)?");
foo = input.next().charAt(0);
continue;
}
else
{
break;
}
}
return fact;
}
}
更改后:
import java.util.Scanner;
public class factorial
{
public static void main ( String [] args )
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number you want to take the factorial of: ");
int num = input.nextInt();
int fact = 1;
System.out.printf("%d! = %d\n ", num, Factorial(num, fact));
System.out.print("Do another factorial (Y,N)? ");
char foo = input.next().charAt(0);
while (foo != 'N')
{
System.out.print("Do another factorial (Y,N)? ");
foo = input.next().charAt(0);
System.out.print("Enter a number you want to take the factorial of: ");
num = input.nextInt();
System.out.printf("%d! = %d\n", num, Factorial(num, fact));
}
}
public static int Factorial(int num, int fact)
{
for (int i = 1; i <= num; i++)
{
fact *= i;
}
return fact;
}
}
输出仍然有一些问题:
最佳答案
您可以计算阶乘,但从不打印它:
System.out.printf("%d! = %d\n ", num, fact, Factorial(num, fact));
应该
System.out.printf("%d! = %d\n ", num, Factorial(num, fact));
此外,您的
Factorial
函数未使用fact
参数,因此您应将其删除,并在函数内部声明一个局部变量。最后,在顶层而不是在
Factorial
函数内部,询问“您想要另一个阶乘”吗?您的代码也不使用用户输入的字符:您将需要一个循环来检查用户的输入,并在输入Y
时继续执行。关于java - Java阶乘输出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15808205/