- 考虑下面两个无限序列。
1.0 + 1.0/2.0 + 1.0/3.0 + 1.0/4.0 + . . .
1.0 - 1.0/2.0 + 1.0/3.0 - 1.0/4.0+ . . .
编写一个程序,计算这两个无限序列的总和,直到到达某次数。提示:奇数个 - 1 得 - 1, 偶数个 - 1 相乘得 1。让用户交互地输入指定的次数,当用户输入 0 或负值时结束查看输入 100 项、1000 项、10000 项后的总和,是否发现每个序列都收敛于某值?
#include<stdio.h>
int main()
{
int length;
double sum_a =0.0,sum_b=0,sum_c=0,sum=0;
printf("Enter the limit length:");
scanf("%d",&length);
for(;length>0;scanf("%d",&length))
{
sum_a=0.0;
sum_b=0.0;
sum_c=0.0;
sum=0;
for(int i=1;i<=length;i++)
{
sum_a=sum_a+1.0/i;
}
for(int i=1;i<=length;i++)
{
if(i%2 != 0)
{
sum_b=sum_b+1.0/i;
}
else
{
sum_c=sum_c-1.0/i;
}
}
printf("The sum_a for 1.0+1.0/2.0...+1.0/n %d is %1f\n",length,sum_a);
printf("The sum_b for 1.0+1.0/3.0+...+1.0/n-1 %d.0 is %1f\n",length,sum_b);
printf("The sum_c for -1.0/2.0-...-1.0/n %d.0 is %1f\n",length,sum_c);
printf("The sum_b+sum_c= %1f\n",sum_c+sum_b);
printf("Enter the limit length sum = sum_a+sum_b+sum_c=%f:\n",sum_a+sum_b+sum_c);
printf("Enter the limit length:");
}
printf("\nDone!\n");
return 0;
}
运行结果
开始运行...
Enter the limit length:100
The sum_a for 1.0+1.0/2.0...+1.0/n 100 is 5.187378
The sum_b for 1.0+1.0/3.0+...+1.0/n-1 100.0 is 2.937775
The sum_c for -1.0/2.0-...-1.0/n 100.0 is -2.249603
The sum_b+sum_c= 0.688172
Enter the limit length sum = sum_a+sum_b+sum_c=5.875550:
Enter the limit length:1000
The sum_a for 1.0+1.0/2.0...+1.0/n 1000 is 7.485471
The sum_b for 1.0+1.0/3.0+...+1.0/n-1 1000.0 is 4.089059
The sum_c for -1.0/2.0-...-1.0/n 1000.0 is -3.396412
The sum_b+sum_c= 0.692647
Enter the limit length sum = sum_a+sum_b+sum_c=8.178118:
Enter the limit length:10000
The sum_a for 1.0+1.0/2.0...+1.0/n 10000 is 9.787606
The sum_b for 1.0+1.0/3.0+...+1.0/n-1 10000.0 is 5.240352
The sum_c for -1.0/2.0-...-1.0/n 10000.0 is -4.547254
The sum_b+sum_c= 0.693097
Enter the limit length sum = sum_a+sum_b+sum_c=10.480703:
Enter the limit length:0
Done!
运行结束。