无法解决递归数学表达式
我正在解决简单的数学任务,并且遇到了一些问题。我已经编写了递归函数,但我没有得到与计算器相同的结果。例如n=2,a =2。有人可以帮助我吗?
任务:
1/a + 1/(a+1) +...+ 1/(a(a+1)...(a+n))
这是到目前为止我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _02__Part_A_
{
class Program
{
float res = 1;
public float func3(int n, int a)
{
if (n == 0)
return 1 / (a * res);
res = res * (a + n);
n--;
return func3(n, a);
}
static void Main(string[] args)
{
Program a = new Program();
float resOFfunc3 = (float)0.5;
string n = Console.ReadLine();
string ak = Console.ReadLine();
for (int nn = int.Parse(n); nn > 0; nn--)
{
resOFfunc3 += a.func3(nn, int.Parse(ak));
}
Console.WriteLine(resOFfunc3.ToString());
}
}
}
I'm solving simple math task, and I have faced with some problems. I have written recursive function, but I don't get same result as in calculator. For instance n=2,a =2. Can anybody help me?
Task:
1/a + 1/(a+1) +...+ 1/(a(a+1)...(a+n))
Here's my code so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _02__Part_A_
{
class Program
{
float res = 1;
public float func3(int n, int a)
{
if (n == 0)
return 1 / (a * res);
res = res * (a + n);
n--;
return func3(n, a);
}
static void Main(string[] args)
{
Program a = new Program();
float resOFfunc3 = (float)0.5;
string n = Console.ReadLine();
string ak = Console.ReadLine();
for (int nn = int.Parse(n); nn > 0; nn--)
{
resOFfunc3 += a.func3(nn, int.Parse(ak));
}
Console.WriteLine(resOFfunc3.ToString());
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一定是递归函数吗?它可以在没有递归的情况下完成:
我还没有测试过它,但它是一个非常简单的算法,所以它应该可以工作。
Does it have to be recursive function? It can be done without recursion:
I haven't tested it, but it's quite a simple algorithm so it should work.
我已经模拟了你的情况:
你不需要将res设置为全局变量,否则为什么首先要设置递归函数?
您需要 2 个递归函数
您只需调用 func4。
I have simulate your case:
You dont need to make res as global variable, otherwise why make recursive functions in first place?
You need 2 recursive functions
You just call func4.
您需要重置 for 循环内的 res 变量
you need reset the res variable inside the for loop
如果没有必要,我不建议使用递归。我尝试将其表示为循环,因为递归可能会导致堆栈溢出,具体取决于输入(特别是如果参数按值传递)。
例如:
I wouldn't recommend using recursion, if it is not neccesary. I'd try to express it as loop, because recursion may lead to stackoverflow depending on the input (especially if the parameters are passed by value).
For example: