其实这个题目和上面那个是一样的
/*
1/1-1/2+1/3-1/4+...1/n;
*/
int n = 1;
double sum = 0;
double frac = 0;
int i = 1; scanf_s("%d", &n); while (i < (n + 1)) //1到n
{
if (i % 2 == 0)
{
frac = -1.0 / i;
}
else
{
frac = 1.0 / i;
} sum = sum + frac;
i++;
}
printf("sum is %f", sum);
update 2018.10.2
昨天看到一个题目和这个类似。里面不用if判断。
#define N 3
int main(void)
{
double data;
int i;
double sum = ;
int mul=; for (i = ; i < N; i++,mul*=-)
{
data = 1.0 / (i + );
data = data * mul;
sum = sum + data;
} printf("%f",sum); return ;
}