Java嵌套时循环和因子初学者

问题描述 投票:0回答:1

我在循环中工作。我从一个初始while循环开始,打印出给定数字的阶乘。代码如下。我现在试图添加第二个循环,这将是10个数字(即,如果输入数字4,它将打印出数字4到14的阶乘)。我知道循环应该从我已经拥有的开始,但我真的不知道从那里去哪里。我插入了我认为是第一个循环的开头。我是编码的新手,所以任何和所有的帮助都表示赞赏

现有代码:

import java.util.Scanner;

public class MyClass 
{
    public static void main(String args[]) 
    {
        Scanner myScanner = new Scanner(System.in)

        while (count <10)
        {
            int number = myScanner.nextInt();
            int fact = 1;
            int i = 1;

            while(i<=number)
            {
                fact = fact * i;
                i++;
            }
            System.out.println("Factorial of "+number+" is: "+fact);
        }
   `}
}
java while-loop nested-loops factorial
1个回答
0
投票

- 你需要在循环之外移动number = myScanner.nextInt(),这样它就不会在每次迭代时都要求新的输入。

- 你需要定义countint count = 0;)

-Loop直到count<= 10。

- 在循环结束时增加countnumber

Scanner myScanner = new Scanner(System.in);
int count = 0;
int number = myScanner.nextInt();
while (count <=10) {

     int fact = 1;
     int i = 1;

     while(i<=number) {         
         fact = fact * i;
         i++;
     }
     System.out.println("Factorial of "+number+" is: "+fact);
     number++;
     count++;
}

输出:(以4为输入)

Factorial of 4 is: 24
Factorial of 5 is: 120
Factorial of 6 is: 720
Factorial of 7 is: 5040
Factorial of 8 is: 40320
Factorial of 9 is: 362880
Factorial of 10 is: 3628800
Factorial of 11 is: 39916800
Factorial of 12 is: 479001600
Factorial of 13 is: 1932053504
Factorial of 14 is: 1278945280

但是我们可以对此进行优化。 5!等于4! * 5.所以知道这一点我们就不能在循环中重置ifact。如果我们输入4,在第一次迭代之后,fact将等于4!并且i将等于5.如果只是不重置它们,在下一次迭代中我们将简单地将fact(4!)乘以5。然后i将变为6并且while循环将终止。然后这将继续,直到外部while循环终止。

int fact = 1;
int i = 1;
while (count <=10) {       
     while(i<=number) {            
         fact = fact * i;
         i++;
     }
     System.out.println("Factorial of "+number+" is: "+fact);
     number++;
     count++;
}

使用4作为输入,这将减少内部while循环中的迭代量,从99减少到14。

© www.soinside.com 2019 - 2024. All rights reserved.