#include
#include
void main()
{
int Num,i,j;
double dResult;
dResult = 0;
printf("Please Enter a Number:\n");
scanf("%d",&Num);
j = 0;
for(i=1;i<=Num;i++){
j = j + i;
dResult += (i+0.0)/j;
}
printf("The Result is %lf",dResult);
getch();
return;
}
其中dResult += (i+0.0)/j;
这一句中,i+0.0是一个类似于强制类型转换的操作,因为C中如果整数除以整数结果肯定为整数,不会为double型。当然也可以将这一句修改为dResult += (double)i/j;
#include
double f(int n)
{
int i;
double sum=0.0;
for(i=1; i<=n; i++) {
sum+= i;
}
return sum;
}
int main()
{
int n;
int i;
double sum=0.0;
printf("input n: ");
scanf("%d", &n);
for(i=1; i<=n ; i++) {
sum += i/f(i);
}
printf("1/f(1)+...+%d/f(%d) = %lf\n", n, n, sum);
return 0;
}