2016-07-23 8 views
-3
1 
1 2 1 
1 3 3 1 

n行Javaパターン。パターン

Iが行わロジックコード:

import java.io.*; 
class pat { 
    public static void main(String[] args) throws IOException { 
     BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); 
     int n,p=0; 
     System.out.println("Enter value of n"); 
     n=Integer .parseInt(in.readLine()); 

     for(int i=0;i<n;i++) 
     { 
      for(int j=0;j<n-i;j++) 
      { 
       System.out.print(" "); 
      } 
      for(int k=0;k<=i;k++) 
      { 
       System.out.print((int)Math.pow(11,p)); 
      } 
      System.out.println(); 
      p++; 
     } 
    } 
} 
+3

質問は...? – Andreas

+1

私は、[パスカルの三角形](https://en.wikipedia.org/wiki/Pascal%27s_triangle)に対して '1 1'という行を見逃したと思います。 –

+0

投稿方法や質問方法をご覧ください – karan

答えて

0

を私はパスカルの三角形の係数が求められていることを理解しました。これは良い練習問題であり、再帰を使って適切な方法でそれをやりましょう。

import java.util.Scanner; 

public class BinomialPascalTriangle { 

    public static int pascal(int i, int j) { 
     if (j == 0) { 
      return 1; 
     } else if (j == i) { 
      return 1; 
     } else { 
      return pascal(i - 1, j - 1) + pascal(i - 1, j); 
     } 

    } 

    public static void print(int n) { 
     for (int i = 0; i < n; i++) { 
      for (int j = 0; j <= i; j++) { 
       System.out.print(pascal(i, j) + " "); 
      } 
      System.out.println(); 
     } 
    } 

    public static void main(String[] args) { 
     Scanner scanner = new Scanner(System.in); 
     System.out.print("How many rows should the binomial pascal triangle have? "); 
     int row = scanner.nextInt(); 
     print(row); 
    } 
} 

バイナリ展開では以前に計算された2つの値が使用されるため、この質問には再帰が適しています。