2014-08-28 85 views
0

我希望您能帮助我更正此方法的输出。递归版本返回我需要的,但non_recursive版本不返回相同的结果。这里是我的代码:返回1 + 1/2 + 1/3 + ... + 1/n的系列

public static double sum_nr(int n){ 
    int result = 1; 
    for(int i=n-1; i>0; i--){ 
     result += 1/i; 
    } 
    return result; 
} 

public static void main(String[] args){ 
    Scanner scan = new Scanner(System.in); 
    System.out.println("Is the string a palindrome or not? "); 
    String test = scan.nextLine(); 
    System.out.println("Answer: " + isPalindrome_r(test)); 
    System.out.println("Answer: " + isPalindrome_nr(test)); 
    System.out.println("What is the sum of n number: "); 
    int test2 = scan.nextInt(); 
    System.out.println("Answer: " + sum_r(test2)); 
    System.out.println("Answer: " + sum_nr(test2)); 
} 

递归版本时n = 101.6179775280898876

非递归版本n = 102.0

我想这两个既相匹配。你可以帮我吗?

+0

怎么样的递归版本 - 头脑与我们分享它还是应该猜到的? – alfasin 2014-08-28 03:51:10

+0

请将'sum_r()'方法定义添加到您的问题中。 – dimo414 2014-08-28 03:53:05

回答

2

请勿对result使用int。声明它是一个double。另外,对分子使用双字面量词进行分割。这两个问题密谋造成不良行为。特别是,1/i是整数除法,对于所有的i> 1评估为0.如果使用1.0/i,则不会发生这种情况,因为i在划分之前被提升为double

public static double sum_nr(int n){ 
    double result = 1;   // <-- first change 
    for(int i=n-1; i>0; i--){ 
     result += 1.0/i;  // <-- second change 
    } 
    return result; 
} 
+0

代表数学系! – nbro 2014-08-28 04:08:48

0

1/i将1我== 1和0任何由于您使用int我> 1。因此,您的结果为2.

请使用doublefloat来进行计算。

0

以下两个版本返回相同的结果:

public static void main(String[] args) throws IOException { 

     System.out.println(sum_nr(10)); //3.928968253968254 
     System.out.println(sum_r(10)); //3.928968253968254 
    } 

    public static double sum_nr(int n){ 
     double result = 1; 
     for(int i = n; i > 0; i--){ 
      result += 1.0/i; 
     } 
     return result; 
    } 

    public static double sum_r(int n){ 
     if (n == 0) { 
      return 1; 
     } 
     else { 
      return 1.0/n + sum_r(n-1); 
     } 
    }