#include
int main(int argc,char *argv[]){
int i;
double sum;
for(sum=0.0,i=1;i<101;i++)
sum += i&1 ? 1.0/i : -1.0/i;
printf("The result is %g\n",sum);
return 0;
}
本题的要点:1除以一个整数后,结果总是0,所以要把这个整数强制转换为double。JAVA写的,和C是一样的。
public class myTest
{
public static void main(String[] args)
{
double sum=0;
int n=100;
for(int i=1;i<=n;i++)
{
if(i%2==1)
sum=sum+1/(double)i;
else
sum=sum-1/(double)i;
}
System.out.println("sum=:"+sum);
}
}
#include
int main()
{
float s=0,t;
int m,n;
printf("输入数值m:\n");
scanf("%d",&m);
for (n=1;n<=m;n++)
{
if(n%2==1)
t=1/n;
else t=-1/n;
s=s+t;
}
printf("%f\n",s);
return 0;
}