超時代碼(暴力求和)
#include <stdio.h>
#include <stdlib.h>
struct node
{
double data;
struct node*next;
};
struct node* c(int n)
{
struct node*head,*tail,*p;
head=(struct node*)malloc(sizeof(struct node));
head->next=NULL;
tail=head;
int i;
for(i=1; i<=n; i++)
{
p=(struct node *)malloc(sizeof(struct node));
if(i%2!=0)
p->data=1.00/i;
else p->data=(-1.00)/i;
p->next=NULL;
tail->next=p;
tail=p;
}
return head;
}
void sum1(struct node*head)
{
double sum=0;
struct node*p;
p=head->next;
while(p)
{
sum+=p->data;
p=p->next;
}
printf("%.2lf\n",sum);
}
int main()
{
int t,n;
scanf("%d",&t);
struct node*head;
while(t--)
{
scanf("%d",&n);
head=c(n);
sum1(head);
}
return 0;
}
AC代碼
(感覺數學真的是特別特別重要,以後一定要非常非常努力地去學數學嘍。。。。。。)
不過,有一點不明白,爲什麼這題歸納在循環鏈表中?如果用循環鏈表,應該如何求解呢?哪位大神看到,還請不吝賜教,小女子在這裏不勝感激了。
數學補充:
關於正負號確定,還可用一個變量,如f。初始時f=1,循環f=-f;(這樣f就會在1和-1中變換)
/*
補充一下:類似1-1/2+1/3-1/4+......+1/n爲交錯級數
n越大,總和值越小,爲收斂級數
當n>155時,由於本題只需要保存小數點後兩位,故1/155及以後的數都近似爲0;
*/
#include <stdio.h>
#include <stdlib.h>
struct node
{
double data;
struct node*next;
};
double c(int n)
{
struct node*head,*tail,*p;
head=(struct node*)malloc(sizeof(struct node));
head->next=NULL;
tail=head;
int i;
double sum=0;
for(i=1; i<=n; i++)
{ if(i>=155) break;//大約到了155左右,1/155保留小數點後兩位爲0.00.
else
{
p=(struct node *)malloc(sizeof(struct node));
if(i%2!=0)
p->data=1.00/i;
else p->data=(-1.00)/i;
p->next=NULL;
tail->next=p;
tail=p;
sum+=p->data;
}
}
return sum;
}
int main()
{
int t,n;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
double sum=c(n);
printf("%.2lf\n",sum);
}
return 0;
}