C Primer Plus 第六章课后习题

  1. 考虑下面两个无限序列。
    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!

运行结束。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值