2015-07-10 75 views
-2

代碼中的錯誤是什麼?它不會打印第一,第三,第五......行中的最後一項。代碼中的錯誤是什麼?它不打印第一,第三,第五......行中的最後一項

public class Pattern { 

    public static void main(String args[]) { 
     int i = 1; 
     for(i = 1; i<5; i++) { 
      for(int j =i*i/2 - i/2 + 1; j < i*i/2 + i/2 +1 ; j++) { 
       System.out.print(j + "\t"); 
      } 
      System.out.println(); 
     } 
    } 

} 
+2

什麼是當前輸出?你在期待什麼?你想做什麼? –

+0

你期望輸出什麼? – Bgvv1983

+0

7,8,9和10仍然小於11 - 這是您的方法中的檢查。這就是爲什麼沒有換行符。但是你想實現什麼?可能它可以變得更容易? – swinkler

回答

0

首先 - 有希望自己只是4行,不是5的另一件事,最後「術語」不因分割整數打印。像1/2將返回0,而不是1

1

i = 1對於該算法給出:

i * i/2 = 1 * 1/2 = 0.5 

作爲i爲整數,實際值是0

同與所有其他奇數數字爲3和5.

可以使用雙精度或舍入或更改數學。

0

運行該代碼,看看for循環

public static void main(String args[]) throws Exception { 
     int i = 1;  
     for (i = 1; i < 5; i++) { 
      int throughLoop = 0; 
      int jInitial = i * i/2 - i/2 + 1; 
      int jCheck = i * i/2 + i/2 + 1; 
      for (int j =jInitial ; j < jCheck; j++) { 
       System.out.print(j + "\t"); 
       throughLoop++; 
      } 
      //jInitial - jCheck because check is less than not less or equal 
      System.out.println("Expected times through loop is " + (jCheck - jInitial) + " Actual through loop " + throughLoop+ " Check was :less than" +jCheck); 
      throughLoop = 0; 
     } 

    } 

發生在什麼就像有人問你,什麼是預期的結果。這可能是你需要小於或等於不小於for(int j =i*i/2 - i/2 + 1; j <= i*i/2 + i/2 +1 ; j++),但這只是我猜不知道你期望輸出是什麼。

0

試試這個代碼

public class Pattern { 

public static void main(String args[]) { 
    float i = 1; 
    for(i = 1; i<=5; i++) { 
     for(float j =((i*i/2) - i/2 + 1); j < ((i*i/2) + i/2 +1) ; j++) { 
      System.out.print((int)j + "\t"); 
     } 
     System.out.println(); 
    } 
} 

} 

你試圖從小數點這是唯一可能的浮動打印整數值。

+0

而我在分配給5之前沒有使用=符號,所以它只迭代了4次。 –

相關問題