用C++编写程序函数求表达式1-1⼀2+1⼀3-1⼀4+1⼀5-1⼀6+1⼀7-...+1⼀n的值

2024-12-17 03:18:56
推荐回答(2个)
回答1:

int fun(int n)
{
double sum = 0.0;
int k = 1;
for(int i = 1; i <= n; i++)
{
sum += (1.0/double(i))*k;
k = k*(-1);
}
return sum;
}

回答2:

float Fun(int n)
{
if(n==1) return 1.0f;
int iCoffie = -1;
float fSum = 1.0f;
for(int i=2; i<=n; i++ )
{
fSum += 1/(float)i*powf(-1,i-1);
}
return fSum;
}