HDU 2011 多项式求和

http://acm.hdu.edu.cn/showproblem.php?pid=2011

Problem Description
多项式的描述如下:
1 - 1/2 + 1/3 - 1/4 + 1/5 - 1/6 + ...
现在请你求出该多项式的前n项的和。
 
Input
输入数据由2行组成,首先是一个正整数m(m<100),表示测试实例的个数,第二行包含m个正整数,对于每一个整数(不妨设为n,n<1000),求该多项式的前n项的和。
 
Output
对于每个测试实例n,要求输出多项式前n项的和。每个测试实例的输出占一行,结果保留2位小数。
 
Sample Input
2
1 2
 
Sample Output
1.00
0.50
 
题解:除号两边 如果都是整型,返回的结果也是除完之后向下取整的结果。
 
代码:
#include <bits/stdc++.h>

using namespace std;

double A(int n)
{
    double sum=0;
    if(n==1)
        return 1;
    else
    {
        for(int j=2; j<=n; j++)
        {
            if(j%2==0)
                sum+=(-1)*1.0/j;
            else
                sum+=1.0/j;
        }
        return (sum+1);
    }
}
int main()
{
    int m;
    cin>>m;
    for(int i=1; i<=m; i++)
    {
        int x;
        cin>>x;
         printf("%.2f\n",A(x));
    }
    return 0;
}

  

猜你喜欢

转载自www.cnblogs.com/zlrrrr/p/9215589.html