2017-12-23 7 views
0

私は階乗を計算するプログラムをコーディングしていますが、最終的な値を実際にプリントアウトする部分を把握していないようです。は、Forループの内部または外部の印刷ステートメントですか?

import java.util.*; 
public class Factorial { 
public static void main(String[] args) { 
    Scanner scan=new Scanner(System.in); 
    System.out.println("Enter integer value: "); 
    int x=scan.nextInt(); 
    System.out.print(x+"!="); 
    int y=0; 


    for(int i=x;i>0;i--) { 
     //y=x*i; 
     y=i*(i-1); 

     if(i==1) 
     System.out.print(i+"="); 

     else 
      System.out.print(i+"*"); 
     //for (int j=2;j>=1 

    } 
    System.out.print(y);   
} 
} 

プログラムは、同様に

すなわちINPUT = 5 OUTPUT = 5!= 5×4×3×2×1 = 120 又は を乗じた数値を表示するようになっていますOUTPUT = 5!= 1 * 2 * 3 * 4 * 5 = 120

答えて

0

最初にする必要があることは、混乱を減らすために中括弧を置いてからインデントすることです。 以下のコードは、あなたが意図していることを行い、必要なコメントがあります。

import java.util.*; 

public class Factorial { 

public static void main(String[] args) { 
    Scanner scan=new Scanner(System.in); 
    System.out.println("Enter integer value: "); 
    int x=scan.nextInt(); 
    System.out.print(x+"!="); 
    int y=1;// Initialize to 1 not 0 as you'll be multiplying. 


    for(int i=x;i>0;i--) { 

     /* 
      Iteration by iteration: 
      i = 5,y= 1-> y = 1*5 
      i = 4,y= 5-> y = 5*4 
      So on... 
     */ 
     y*=(i); 

     if(i==1) 
      { 
       // Print Equal only if its the last number. Since 
        we are going 5*4*3*2*1 =. We need this if to print 
        1 =. 
       System.out.print(i+"="); 

      } 

     else 
      { 
       //For other cases just print Number and *. 
       System.out.print(i+"*"); 

      } 


    } 
    // Print the actual output. 
    System.out.print(y);   



} 

} 
関連する問題