我应该创建一个程序,询问用户一个数字并获取该数字的阶乘,然后询问他们是否想做另一个阶乘(Y,N)。
它应该像这样工作:
- 输入一个数字以乘以:4
- 4!= 24
- 做另一个阶乘(Y,N)?是
- 重复直到输入 N
我的输出是这样的:
- 输入一个数字以求阶乘:
- “做另一个阶乘?(Y,N)?”
4!= 1,无论我输入 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;
}
}
输出还是有一些问题:
- 输入一个数字以乘以:4
- 4!= 24
- 做另一个阶乘(Y,N)?是
- 做另一个阶乘(Y,N)?是
- 输入一个数字以乘以:4
- 4!= 24
- 做另一个阶乘(Y,N)?ñ
- 输入一个数字以求阶乘: