2017-02-20 56 views
1

所以我編寫了Collat​​z序列的代碼,但是我希望能夠識別並打印出序列中出現的最大數字。這裏是我的代碼:Collat​​z序列:哪個數字最大?

import java.util.Scanner; 

public class CollatzSequence { 
    public static void main(String[]args) { 
     Scanner keyboard = new Scanner(System.in); 
     int n,ts = 0; 

     System.out.print("This is the Lothar Collatz Sequnce. Please enter the starting number.\n>"); 
     n = keyboard.nextInt(); 

     do { 
      if (n % 2 == 0) { 
       n = n/2; 
       System.out.println(n); 
      } 
      else { 
       n = n*3 + 1; 
       System.out.println(n); 
      } 
     ts++; 
     } 
     while (n != 1);  
     System.out.println("Terminated after "+ts+" steps."); 

     } 
    } 

回答

2

創建一個名爲max的變量。初始設置爲n。在每一步中,檢查n > max是否爲maxn

+0

這可能會起作用。謝謝! – jackmasterlooter