簡體   English   中英

這個析因程序有什么問題? 它只是繼續返回原始值

[英]What am I doing wrong with this factorial program? It just keeps on returning back the original value

public static void main (String args[]){

    int num=5;
    int i=num-1;
    int factorial=0;

    while(i>0){

        factorial=num*i;
        i--;
     }
    System.out.println(""+factorial);
}

它一直讓我回頭。5。對不起,如果聽起來像是個小問題,我是編程領域的新手。

更換

factorial=num*i;

num=num*i;

System.out.println(""+factorial);

System.out.println(""+num);

原因

您正在正確運行while循環。 在每次迭代中,您將兩個連續的數字相乘。 但是您將結果存儲在factorial中,每次迭代都會覆蓋它。 所以最后,您得到的是原始號碼。 因此,按照上面的指示進行操作,擺脫factorial變量。

我不會給您解決方案,但是它存儲5是正常的,因為您的最后執行是:

factorial = 5 * 1;

現在,三思而后行。

您正在做錯事,因為它將執行為

    num is 5 and i is 4 // result will be 20
    then num is 5 and i is 3 // result will be 15
    then num is 5 and i is 2 // result will be 10
    then num is 5 and i is 1 // result will be 5
    while loop break

您需要存儲以前的結果,所以使用此

        int num=5;
        int factorial=1;

        while(num>0){

            factorial=num*factorial; // previous result will be store in factorial    
            num--;
         }
        System.out.println(""+factorial);

現在該程序如何工作

       num is 5 and fact is 1 // fact will be 5
        then num is 4 and fact is 5 // fact will be 20
        then num is 3 and fact is 20 // fact will be 60
        then num is 2 and fact is 60 // fact will be 120
        then num is 1 and fact is 120 // fact will be 120
        while loop break

在每個循環中,您都將數字乘以i ,因此最后您將得到num*1 您可以使用num的值初始化結果變量factorial ,並在每個循環中為其分配乘以i值,這將導致從1到num的所有數字相乘(階乘):

public static void main (String args[]){

    int num=5;
    int i=num-1;
    int factorial=num;

    while(i>0){

        factorial=factorial*i;
        i--;
    }

    System.out.println(""+factorial);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM