问题描述
我做了这个,但它返回了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;
}
推荐答案
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系列的总和。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!