2014-10-06 76 views
0

我試着拍了一些,並打印的奇數這樣的:打印奇數在倒直角形成

if i take 5 as a number it should give this: 

    1 3 5 
    3 5 
    5 

    and if i take 9 it should do the same thing: 

    1 3 5 7 9 
    3 5 7 9 
    5 7 9 
    7 9 
    9 

這是我到目前爲止,我被卡住。我不能得到的5到3後打印,並用5結束它的三角形:

public class first{ 
    static void afficher(int a){ 
    for(int i=1;i<=a;i++){ 
     if(i%2!=0){ 
      System.out.printf("%d",i); 
     } 
    } 
    System.out.println(); 

    for(int j=3;j<=a-2;j++){ 
     if(j%2!=0){ 
      System.out.printf("%d",j); 
     } 
    } 
} 




    public static void main(String[]args){ 
     afficher(5); 


    } 

} 

此打印:

1 3 5 
3 
+0

由於您正在打印「表面」,因此您期望兩個嵌套的「for」。 – 2014-10-06 04:18:02

+0

for循環for循環? – user3268216 2014-10-06 04:19:07

+0

是的,確實.... – 2014-10-06 04:19:26

回答

1

如果打印表面(2D因而),一個期望該算法運行在時間複雜度爲O(n^2)。因此,兩個嵌套for S:

public class first{ 
    static void afficher(int a){ 
     for(int i = 1; i <= a; i += 2) { 
      for(int j = i; j <= a; j += 2){ 
       System.out.print(j); 
       System.out.print(' '); 
      } 
      System.out.println(); 
     } 
    } 
} 

人們可以通過不檢查if的數量是奇數,但服用的2步驟優化算法一點。

請參閱demo

0
The reason it is printing as follows because: 

1 3 5 -> your i loop runs here (from 1 to 5) 
3  -> your j loop runs here (from 3 to (less than OR equal to 5)) 

So i suggest the following: 

1. Use 2 nested loops (for universal values): 
i running from 1 to the input number increasing by 2 
j running from i to the input number increasing by 2 also ending with line change'/n' 

2. Keep a check whether the input number is odd or not. 

Hope that helps ! 
0

您必須使用嵌套的for-loops來解決此問題。通過下面的代碼去,

public class OddNumberLoop { 

public static void main(String[] args) { 

    Scanner inpupt = new Scanner(System.in); 

    System.out.print("Input the starting number : "); 
    int start = inpupt.nextInt(); 
    for(int i = 1 ; i <= start; i += 2){ 
     for(int x = i; x <= start; x += 2) System.out.print(x+ " "); 
     System.out.println(); 
    } 

} 

}

好運!