2015-02-09 64 views
-1

仍在學習,我似乎無法總結我的腦袋上似乎像一件容易的事。 的computeMethods方法的就是IM完全以難倒,但是相反的方法,我只是不斷取回相同的整數而不會被逆轉。編程作業遞歸

/**************************** 
     * For Method Computemethods1 i must compute series 
     * b(x)=1/3+2/5+3/7..... +x/2x+1 
     * For method ComputeMethod2 
     * 1/2+2/3+......... x/(x+1) 
     *******************************/ 
     public static int computeMethod1(int x){ 
     if (x==0) 
      return 0; 
     if (x==1) 
      return 1; 
     return computeMethod1(x-1/3/(x-1))+computeMethod1(x-2/3/(x-2)); 
     } 


     public static int computeMethod2(int x){ 
     if (x==0) 
      return 0; 
     return computeMethod2((x-1)/(x-1)+1)+computeMethod2((x-2)/(x-2)+1); 
     } 
     /******************** 
     * For method reverseMethod i must reverse a user given int 
     **********************/ 
     public static int reverseMethod(int x){ 
     int reversedNum=0; 
     if (x!=0) 
      return x; 
     reversedNum=reversedNum *10 +x%10; 
     return reversedNum+reverseMethod(x/10); 


     } 
     /****************** 
     * For method sumDigits i must use recursion 
     * to sum up each individual number within the int 
     ********************/ 

     public static long sumDigits(long n){ 
     if(n==0) 
      return 0; 
     if (n==1) 
      return 1; 
     else 
      return n+sumDigits(n-1); 
     } 
    } 
+0

'X-1/3'可能與整數除法的問題?嘗試使用'float'或'double'數字,即'x-1。/ 3.'並相應地更改方法的參數。另外,sumDigits似乎有點偏離...實際上,它更像是「從1到n的所有數字的總和」。 – 2015-02-09 09:29:47

+0

你的問題是什麼?您應該指定什麼不按預期工作。另外,請刪除不相關的代碼。 – 2015-02-09 09:30:39

回答

2

對於反向方法,使用的是:if (x!=0) return x;

可能是你需要使用方法:if (x==0) return x。所以邏輯是,如果給定的參數是0,則返回0,否則返回倒數。

P.S:正如有人在comentaries提到的,請照顧的類型,所以爲師,你可以更好地使用floatdouble,並照顧業務優先級爲正確的結果,所以(x+1)/2將從x+1/2不同。

0

對於您的每一個方法,跟進您的小x代碼。

例如,computeMethod1應該返回:

  • 1/3x == 1,而目前它只是簡單地返回1(注意,返回類型將需要比int以外的東西。)。

  • 1/3 + 2/5x == 2

  • 1/3 + 2/5 + 3/7x == 3

對於每個x,注意我們如何使用以前的結果,即computeMethod1(x - 1)

當你遇到的代碼看起來並沒有達到你期望的程度時,讓你的代碼更簡單更簡單,直到你能夠縮小問題的位置,然後希望問題會變得明顯,或者在線文檔可以告訴你。