2016-07-25 146 views
0

我是一個初學者,試圖編寫一個java代碼來生成輸出數字,這個輸出數字是2和5的主要因素。Java「For」循環輸出重複

例如,如果輸入是,那麼輸出應該是。 但是,每當我打印我的輸出,結果將是2 5 4 5 8 5.

請諮詢我出錯的地方。 謝謝

import java.util.Scanner; 

class twofive { 
    public static void main(String [] args) { 
    Scanner sc = new Scanner(System.in); 
    System.out.print("Enter n:"); 
    int n = sc.nextInt();              
    double num = 0; 
    double num2 = 0; 
    for (int i = 1; (((Math.pow(2,i))<= n) || ((Math.pow(5,i)) <=n) || (((Math.pow(2,i))<= n) && ((Math.pow(5,i)) <=n))) ; i++) { 
     if ((Math.pow(2,i)) <= n)             
     num = (Math.pow(2,i)); 
     int convert = (int) num;{ 
     System.out.print(convert + " "); 
     } 
     if ((Math.pow(5,i)) <= n) 
     num2 = (Math.pow(5,i)); 
     int convert2 = (int) num2; 
     {System.out.print(convert2 + " "); 
    } 
    } 
} 
} 
+3

8的整數*因子是** 1 2 4 8 **。 8的* prime *分解是* 2 2 2 *或* 2^3 *。你的代碼做了其他的事情:它會產生小於或等於給定整數的2和5(以及素數2和5)的所有*組合。 –

回答

0

您查看@AmedeeVanGasse的評論後,你需要修復您的括號。

public static void main(String [] args) { 
    Scanner sc = new Scanner(System.in); 
    System.out.print("Enter n:"); 
    int n = sc.nextInt();              
    double num = 0; 
    double num2 = 0; 
    for (int i = 1; Math.pow(2,i))<= n) || ((Math.pow(5,i)) <=n) || (((Math.pow(2,i))<= n) && ((Math.pow(5,i)) <=n))) ; i++) { 
     if ((Math.pow(2,i)) <= n) {             
     num = (Math.pow(2,i)); 
     int convert = (int) num; 
     System.out.print(convert + " "); 
     } 
     if ((Math.pow(5,i)) <= n) { 
      num2 = (Math.pow(5,i)); 
      int convert2 = (int) num2; 
      System.out.print(convert2 + " "); 
     } 
    } 
} 

您還應該查看邏輯在for循環和if語句。他們充滿了不必要的冗餘。