2015-01-10 172 views
0

我剛開始學習java,出於某種原因,我的程序在編譯時不會返回任何結果。爲什麼我的程序不會返回任何內容?

目標: 寫稱爲printPowersOf2方法接受最大數量作爲參數,並從打印20(1)到那個最大功率,包括2每個功率。例如,請考慮以下呼叫:

printPowersOf2(3); 
printPowersOf2(10); 

這些調用應產生以下的輸出:

1 2 4 8 
1 2 4 8 16 32 64 128 256 512 1024

問題也可以從here

找到我的代碼:

public class Test{ 
    public static void main(String[] Args){ 
     printPowersOf2(3); 
     printPowersOf2(10);   
    } 
    public static int printPowersOf2(int num){ 
     double b = Math.pow(2,num); 
     int a = (int)b; 
     return a; 
    } 
} 

回答

3

它確實返回值,但這不是你想要的。你想打印吧!你應該使用打印在一個循環中值:

System.out.printf("%d ", a); 

,而不是return a;全功能:

public static void printPowersOf2(int num) { 
    for (int i = 0; i < num; i++) { 
     System.out.print("%d ", Math.pow(2, i)); 
    } 
    System.out.println(); // for the line break 
} 

不需要double s,因爲這些數字是完美的正方形。

1

我覺得你的代碼應該是:

public class Test{ 
    public static void main(String[] Args){ 
     printPowersOf2(3); 
     printPowersOf2(10);   
    } 
    public static void printPowersOf2(int num){ 
     for(int i = 0; i <= num; ++i) 
     { 
      double b = Math.pow(2,num); 
      System.out.print(b + " "); 
     } 
    } 
} 

您不必返回任何東西。你只能在函數內打印。

相關問題