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

n行Java模式。代碼用於圖案

我提出的邏輯:

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

我想,你錯過了一條[Pascal三角形]的'1 1'(https://en.wikipedia.org/wiki/Pascal%27s_triangle)。 –

+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); 
    } 
} 

由於二項式擴展使用兩個先前計算的值,遞歸對於這個問題是很好的。