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());
}
}
}
you need reset the res variable inside the for loop