用C语言编写:计算前N个自然数的倒数之和

2024-12-18 18:06:27
推荐回答(3个)
回答1:

#include

double fun1(int n)
{
int i;
double sum = 0;
for (i = 1; i <= n; i++)
sum += 1.0/i;
return sum;
}

int main(void)
{
int n;
printf("请输入一个整数:");
scanf("%d",&n);
printf("前%d个自然数的倒数之和 = %lf\n",n,fun1(n));
}

回答2:

#include

double
fun1(int
n)
{
int
i;
double
sum
=
0;
for
(i
=
1;
i
<=
n;
i++)
sum
+=
1.0/i;
return
sum;
}
int
main(void)
{
int
n;
printf("请输入一个整数:");
scanf("%d",&n);
printf("前%d个自然数的倒数之和
=
%lf\n",n,fun1(n));
}

回答3:

#include
void main()
{int i,n,s;
double sum;
printf("请输入整数n:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{s=1.0/i;
sum+=s;
printf("前%d个自然数倒数之和 =%f\n",n,sum)
}
}