如何递归计算1 + 1 / 2-1 / 3 + 1 / 4-1-5 ..... 1 / N系列的总和。 [英] How Do I Compute Sum Of Series 1+1/2-1/3+1/4-1-5.....1/N Recursively.

查看:434
本文介绍了如何递归计算1 + 1 / 2-1 / 3 + 1 / 4-1-5 ..... 1 / N系列的总和。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了这个,但它返回了n的值。告诉我该怎么做???



int sum_of_series(int n)

{

static int value = 0;

static int answer;

static int answer1;

if(n == 1)

{

返回1;

}

其他

{

答案= 1 / 1 + sum_of_series(n-1);

返回答案;

}

//返回值;

}

I did this but it is returning the value of n. Tell me what to do???

int sum_of_series(int n)
{
static int value = 0;
static int answer;
static int answer1;
if(n == 1)
{
return 1;
}
else
{
answer = 1/1+sum_of_series(n-1);
return answer;
}
//return value;
}

推荐答案

嗯。你看过你的代码了吗?
Um. Have you looked at your code?
answer = 1/1+sum_of_series(n-1);



运算符优先级表示:


Operator precedence says that is:

answer = (1/1)+sum_of_series(n-1);

因为你想要:

since you want:

1+1/2-1/3+1/4...

你需要在某个时刻开始使用1 / N ......然后你可以担心标志改变......

you need to start by using 1/N at some point... Then you can worry about the sign changing...


public double sum_of_series(int n)
     {
         //the condition where recursion stops
         if (n == 1)
         {
             return 1;
         }
         double result;
         //if the divisor is even, sum the result else subtract it.
         if (n % 2 == 0)
         {
             result = this.sum_of_series(n - 1) + 1 / (double)n;
         }
         else
         {
             result = this.sum_of_series(n - 1) - 1 / (double)n;
         }

         return result;
     }


这篇关于如何递归计算1 + 1 / 2-1 / 3 + 1 / 4-1-5 ..... 1 / N系列的总和。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆