2017-12-23 10 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);   



} 

}