繁体   English   中英

Java嵌套While循环和阶乘初学者

[英]Java Nested While Loops and Factorials Beginner

我正在嵌套while循环。 我从一个初始的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);
        }
   `}
}

-您需要将number = myScanner.nextInt()循环,以免每次迭代都要求新的输入。

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

-循环直到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将变成六岁, 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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM