2014-09-11 58 views
3
public class numPattern { 
    public static void main(String[] args) { 
     int digit1 = 2; 
     int digit2 = 7; 
     int tal = 0; 

     System.out.print(digit1 + " "); 
     System.out.print(digit2 + " "); 

     while (tal < 550) { 
      tal = digit1 + digit2; 

      System.out.print(tal + " "); 

      digit1 = digit2; 
      digit2 = tal; 
     } 
    } 
} 

此輸出2, 7, 9, 16, 25, 41, 66......453 and 733號碼模式截止

的問題應該在453停止,因爲733是大大超過550

什麼命令將確保該程序在453結束,以滿足更大的或等於550我試圖尋找?

回答

0

簡單的變化:

while (tal < 550){ 
    tal = digit1 + digit2; 

    System.out.print(tal + " "); 
    digit1 = digit2; 
    digit2 = tal; 
} 

到:

while (tal < 550) { 
    System.out.print(tal + " "); 

    digit1 = digit2; 
    digit2 = tal; 
    tal = digit1 + digit2; 
} 

tal的初始化:
int tal = 0,到int tal = digit1 + digit2;

+0

這將打印「2 7 *** 0 *** 9 16 25 41 66 107 173 280 453「(即有多餘的「0」打印出來作爲第一個數字) – 2014-09-11 12:51:21

+0

謝謝指出。我已經更新了答案 – qbit 2014-09-11 15:03:47

+0

if語句是否可以解決此問題? – hobo 2014-09-11 15:19:54

1

只是跳過的digit2打印輸出,初始化tal爲相同的值,並重新排列在你的循環中的語句:

int digit1 = 2; 
System.out.print(digit1 + " "); 

int digit2 = 7; 
int tal = digit2; 
while (tal < 550) { 
    System.out.print(tal + " "); 
    tal = digit1 + digit2; 
    digit1 = digit2; 
    digit2 = tal; 
} 
3

增加的tal值在while

int digit1 = 2; 
    int digit2 = 7; 
    int tal = 0; 

    System.out.print(digit1 + " "); 
    System.out.print(digit2 + " "); 

    while((tal = digit1 + digit2)< 550) 
    { 

     System.out.print(tal + " "); 

     digit1 = digit2; 
     digit2 = tal; 
    } 
0
int digit1 = 2; 

System.out.print(digit1 + " "); //it will print digit1 
do not print digit2 

int digit2 = 7; 
int tal = digit2; 
while (tal < 550) { 
    System.out.print(tal + " "); 
    tal = digit1 + digit2; 
    digit1 = digit2; 
    digit2 = tal; 
} 

因爲在循環首先增加值,然後打印因此前的狀態說假它已經在tal = 443時打印該值,然後它進入while循環執行總和並打印它,然後去檢查值

之後首先打印該值,然後執行總和並檢查其是否小於443

+0

這打印出「2 7 *** 0 *** 9 16 25 41 66 107 173 280 453」(即,我有一個額外的「0」作爲第一個數字打印出來) – 2014-09-11 12:51:05