我应该创建一个程序,要求用户输入一个数字并取该数字的阶乘,然后询问他们是否想要做另一个阶乘(Y,N)。
它应该像这样工作:
我的输出如下:
4!无论我是否输入Y或N,都= 1。
这是我的代码:
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;
}
}
输出仍有一些问题:
答案 0 :(得分:3)
你计算阶乘,但你从不打印它:
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
时继续。
答案 1 :(得分:1)
这是错误:
System.out.printf("%d! = %d\n ", num, fact, Factorial(num, fact))
您的输出不是Factorial(num, fact)
而是fact
,这应该是:
System.out.printf("%d! = %d\n ", num, Factorial(num, fact))
答案 2 :(得分:0)
删除以下代码行:
扫描仪输入=新扫描仪(System.in); System.out.print(“做另一个因子(Y,N)?”);
来自Factorial方法。答案 3 :(得分:0)
您应该按如下方式重构代码:
应该有一个方法需要int
并返回其阶乘,而不会做任何其他事情。
所有的输入/输出,以及“做另一个因子?”循环,应该在main()
。
这样可以更容易地使逻辑正确。
答案 4 :(得分:0)
这会对你有帮助。
public static void main ( String [] args )
{
String yesno ="Y";
while(yesno.equalsIgnoreCase("y"))
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number you want to take the factorial of: ");
int num = input.nextInt();
System.out.printf("%d! = %d\n ",num,fact(num));
System.out.print("Do another factorial (Y,N)?");
Scanner inputKey = new Scanner(System.in);
yesno = inputKey.nextLine();
}
}
这是阶乘函数:
public static int fact(int num)
{
if(num<=1)
{
return 1;
}else{
return (num*(fact(num-1)));
}
}