您的位置:首页 > 理论基础 > 数据结构算法

多项式求和 链表

2016-07-29 22:59 381 查看
此题有一个坑,就是因为数太大会超时,但试几组数据就会发现,当它到一定的数时,结果就不变了,可以缩小计算范围

多项式求和

Time Limit: 1000MS Memory limit: 65536K

题目描述

多项式描述如下:
1 - 1/2 + 1/3 - 1/4 + 1/5 - 1/6 ……
先请你求出多项式前n项的和。

输入

第一行输入一个数T代表测试数据个数(T<=1000)。接下来T行每行1个数代表n(0<=n< 2^31)。

输出

对于每个输入样例,输出多项式和的结果(结果精确到小数点后两位)。每行输出一个结果。

示例输入

2
1
2


示例输出

1.00
0.50
#include <stdio.h>
#include <stdlib.h>
#include<math.h>
using namespace std;
struct node
{
double data;
struct node *next;
};

int main()
{
int a;
int n,i;
struct node *head,*tail,*p;
scanf("%d",&a);
while(a--)
{
scanf("%d",&n);
if(n>=200)//*******************注意
n=200;
head=(struct node *)malloc (sizeof(struct node));
head->next=NULL;
tail=head;
for(i=1; i<=n; i++)
{
p=(struct node *)malloc(sizeof(struct node));
p->data=pow(-1,i+1)*(1/(double)i);
p->next=NULL;
tail->next=p;
tail=p;

}
double sum=0;
p=head->next;
while(p)
{

sum=sum+p->data;
p=p->next;
}
printf("%.2lf\n",sum);

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息