这就是我应该做的事情:
编写一个Java程序,它将计算某些数字的阶乘数n(来自用户的输入,仅接受范围1 - 10)。对于输入中的每个有效数字,输出应为n!的值。你的程序应该使用一个循环,允许用户输入多个数字(计数控制或哨兵控制,你的选择)
这就是我现在所拥有的:
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
int num, result = 1;
String str;
System.out.print("Do you want to start? (y/n) ");
str = console.next();
System.out.println();
while(str.charAt(0) == 'y')
{
System.out.print("Enter an integer (1 - 10): ");
num = console.nextInt();
if(num < 1 || num > 10)
{
System.out.print("NUMBER OUT OF RANGE!");
num = console.nextInt();
}
else
{
int i = 2;
while(i <= num)
{
result = result * i;
i++;
}
System.out.println(num + "! = " + result);
System.out.println();
System.out.print("Do you want to continue? ");
str = console.next();
}
System.out.println();
}
}
但这是我的结果:
Do you want to start? (y/n) y
Enter an integer (1 - 10): 1
1! = 1
Do you want to continue? y
Enter an integer (1 - 10): 2
2! = 2
Do you want to continue? y
Enter an integer (1 - 10): 3
3! = 12
Do you want to continue? y
Enter an integer (1 - 10): 4
4! = 288
我无法让输出显示正确的结果,这是我对程序的唯一问题。此外,它会在您第一次要求输入整数时显示正确的结果,但在此之后,一切都会出错
答案 0 :(得分:0)
您需要在外部result = 1
循环内设置while
,而不是在它之前。这里发生的事情是,您乘以的数字乘以外部while
循环的前一次迭代的结果。
答案 1 :(得分:0)
在迭代新值时,您没有重置while(str.charAt(0) == 'y')
{
result =1;
。
在开始计算阶乘之前,只需将结果重置为1
例如 -
def parallelize[T](seq: Seq[T],
numSlices: Int = defaultParallelism)
(implicit arg0: ClassTag[T]): RDD[T]
答案 2 :(得分:0)
试试这段代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String str;
System.out.print("Do you want to start? (y/n) ");
str = console.next();
System.out.println();
int num, result;
while (str.charAt(0) == 'y') {
System.out.print("Enter an integer (1 - 10): ");
num = console.nextInt();
while (num < 1 || num > 10) {
System.out.println("NUMBER OUT OF RANGE!");
System.out.print("Enter an integer (1 - 10): ");
num = console.nextInt();
}
int i = 2;
result = 1;
while (i <= num) {
result = result * i;
i++;
}
System.out.println(num + "! = " + result);
System.out.println();
System.out.print("Do you want to continue? ");
str = console.next();
System.out.println();
}
}
}
答案 3 :(得分:0)
我认为你的if语句存在逻辑错误。范围为1-10,if语句应如下所示:
if(userInput>0 && userInput<=10);
此外,正如大卫华莱士所述,你需要在你的内部“阶乘循环”结束后将你的变量i重新初始化为1。通过这种方式,只要在循环中进入内部阶乘,你的变量i总是会有1的起始值。
答案 4 :(得分:0)
我会开始,为有效的factorial范围创建一个查找表。这可能是迭代完成的,创建一个fact
数组并填充它。像,
int[] fact = new int[10];
int i;
fact[0] = i = 1;
while (i < fact.length) {
fact[i] = (i + 1) * fact[i - 1];
i++;
}
然后你可以使用Scanner
(打破非整数输入)和fact
查找表之类的无限循环,
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Enter a number 1-10 for the factorial (or a "
+ "non-number to quit): ");
if (!scan.hasNextInt()) {
break;
}
i = scan.nextInt();
if (i < 1 || i > 10) {
System.out.println("NUMBER OUT OF RANGE!");
continue;
}
System.out.printf("%d! = %d%n", i, fact[i - 1]);
}