Calculate the expression:
1 / a + 1 / (a ​​+ 1) + .. + 1 / ((a + 1) ... (a + n))

Example:
Input:
2 1
Output:
0.666667

Example:
Input:
2.1 2
Output:
0.667266

#include <iostream> using namespace std; int main() { int n = 0, i; double a = 0, s, d; cin >> a >> n; s = 1.0 / a; for (i = 1; i < n + 1; i++) { a = a * (a + i); s = s + 1.0 / a; } cout << s << endl; return 0; } 

Could you help me find where I have a mistake?

    3 answers 3

     #include <iostream> using namespace std; int main() { int n; double a, s; cin >> a >> n; s = 1.0/a; a = a + 1; for (int i = 1; i < n; i++) { s = s + (1.0 / a); a = a * (a + i); } cout << s << endl; } 
    • @Just_kiss_me, I corrected my answer, the code to which you answered worked incorrectly. - ivkremer 8:59 pm

    You must have a formula according to the condition

    1 / a + 1 (a + 1) + 1 / (a ​​+ 1) (a + 2) + ... + 1 / (a ​​+ 1) ... (a + n), isn't it?

    You have the same cycle builds, schob not lie

    1 / a + 1 / a (a + 1) + 1 / a (a + 1) (a + 2) + ... + 1 / a (a + 1) ... (a + n)

    The problem is that 0. (6) (well, 0.666667) in this algorithm with a = 2 n = 1 we get exactly in the form that you wrote.

    If to lead to the scheme, the code looks like this:

     #include <iostream> using namespace std; int main() { int n = 0, i; double a = 0, s, d; cin >> a >> n; d = 1; // ! s = 1.0 / a; for (i = 1; i < n + 1; i++) { d = d * (a + i); // ! s = s + 1.0 / d; // ! } cout << s << endl; return 0; } 

      This is the right one. Found the reason:

       #include <iostream> using namespace std; int main() { int n, i; double a, d = 0, c = 1; cin >> a >> n; for (i = 0; i <= n; i = i + 1) { c = c * (a + i); d = d + 1.0 / c; } cout << d << endl; return 0; }