/************************************************************************
*功能:计算序列 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 + ....
* 具体计算到某一次由用户指定
************************************************************************/
#include<stdio.h>
float sum1(int n);
float sum2(int n);
void show(float,float,int);
int main(void)
{
int n = 0;
float sum_1 = 0.0, sum_2 = 0.0;
printf("how many times you want to add:(0--1000000)");
while(scanf("%d",&n) == 1 && n > 0&& n < 1000000)
{
sum_1 = sum1(n);
sum_2 = sum2(n);
show(sum_1,sum_2,n);
printf("input next value(0--1000),q to quit:");
}
return 0;
}
float sum1(int n)
{
float sum = 0.0;
int i = 0;
for(i = 1; i <= n; i++)
{
sum = sum + 1.0/(float)i;
}
return sum;
}
float sum2(int n)
{
int i = 0,t = 1;
float sum = 0.0;
for(i = 1; i <= n; i++)
{
sum = sum + t * 1.0/(float)i;
t = -t;
}
return sum;
}
void show(float sum_1, float sum_2, int n)
{
printf("sum_1 = %f\n",sum_1);
printf("sum_2 = %f\n",sum_2);
}