当前位置:网站首页>Function: find 1-1/2+1/3-1/4+1/5-1/6+1/7-... +1/n

Function: find 1-1/2+1/3-1/4+1/5-1/6+1/7-... +1/n

2022-07-06 14:35:00 |Light|

requirement

Write a function to find 1-1/2+1/3-1/4+1/5-1/6+1/7-…+1/n.

Code

/* * Implement... In this function 1-1/2+1/3-1/4+1/5-1/6+1/7-…+1/n */
 double fun(int n)
 {
    
    double sum=0;
    double b=-1,i,c=-1;
    for(i=1;i<=n;i++)
    {
    
        b = b*c;
        sum = sum+b*(1/i);
    }
    return sum;
 }

 

test

Test input
3
Output
0.83333

原网站

版权声明
本文为[|Light|]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060918542981.html