Java - 因子

时间:2013-11-05 11:01:51

标签: java

我正在打印前10个数字的阶乘,所以它是0 - 9.以下代码适用于我。但我无法使循环使得0的阶乘也在循环内。任何建议表示赞赏。谢谢。

public class fact {

    public static void main(String[] args) { 
        System.out.println("\n\n(f) Loop to print first 10 factorial numbers");

        System.out.println("\nFactorial of 0 is 1");

        int fact = 1; 
        int index = 1; 
        while (index < 10) 

        { 
            fact*=index; 
            System.out.println("Factorial of " + index + " is " + fact); 
            index++; 
        } 
    }
} 

5 个答案:

答案 0 :(得分:1)

如何在if循环中为索引0添加while条件

    int fact = 1; 
    int index = 0; 
    while (index < 10) 

    { 

        if(index == 0)
          System.out.println("\nFactorial of 0 is 1");
        else {
           fact*=index; 
           System.out.println("Factorial of " + index + " is " + fact); 
       }
       index++; 
    } 

答案 1 :(得分:1)

因子0是一种特殊情况,因此最好在循环外打印它,就像现在一样。

答案 2 :(得分:1)

对于大n个数字,找到阶乘及其数字计数。

import java.util.Scanner;
    public class N_Faktorial {
        public static void main(String [] args)
        { 
           int u=1,A[]=new int[9999999];
           Scanner scan =new Scanner(System.in);
           System.out.print("n=");
          int n=scan.nextInt();
          A[1]=1;
        for(int i=1;i<=n;i++) 
        {
           for(int j=1;j<=n;j++) {
                A[j]*=i;
            }           
           for(int j=1;j<=n;j++)
           {
             if(A[j]>9)
              {
              A[j+1]+=A[j]/10;
              A[j]%=10;       
              }
             if(A[u+1]!=0) {
                   u++;
               } 
           }

       }
        System.out.print(n+"! digit count:"+u+"\\n Result: \\n");
         for(int i=u;i>=1;i--)
         {
             System.out.print(A[i]);
         }

        }

    }

答案 3 :(得分:0)

你可以这样做

    int fact = 1; 
    int index = 0; 
    while (index < 10) 

    { 
        fact=(index==0)?1:fact*(index);
        System.out.println("Factorial of " + index + " is " + fact); 
        index++; 
    }         

答案 4 :(得分:0)

factorialList(10);

public static int factorialList(int indexMax) {
    int fact = 1;
    if (indexMax > 0) fact = indexMax * factorialList(indexMax - 1);
    System.out.println("Factorial of " + indexMax + " is " + fact);
    return fact;
}

Fn调用不如循环有效,但我敢打赌它会优化到相同的大小任务。