The "C language" calculates the value of 1/1-1/2+1/3-1/4+1/5 ... + 1/99-1/100.

Source: Internet
Author: User
Tags pow

Note: When calculating 1 to use a double type that is 1.0 .

• Odd even numbers are calculated separately and then merged.

```#include<stdio.h>
int main()
{
int i;
double sum=0,sum1=0,sum2=0;
for(i = 1;i <= 99;i+=2)
{
sum1=sum1+1.0/i;
}
for(i = 2;i <= 100;i+=2)
{
sum2=sum2-1.0/i;
}
sum=sum1+sum2;
printf("%lf",sum);
return 0;
}

```
• Label control +1,-1 with flag.

```#include<stdio.h>
int main()
{
int i;
double sum = 0;
int flag = -1;
for(i = 1;i <= 100;i++)
{
flag*=-1;
sum+=flag*(1.0/i);
}
printf("%lf",sum);
return 0;
}

```
• Use the Function Pow Pow ( -1,i+1) equivalent ( -1) ^ (i+1)

```#include<stdio.h>
#include<math.h>
int main()
{
int i;
double sum = 0;
for(i = 1;i <= 100;i++)
{
sum+=pow(-1,i+1)*(1.0/i);
}
//pow（-1，i+1）相当于（-1）^(i+1)
printf("%lf",sum);
return 0;
}

```

The "C language" calculates the value of 1/1-1/2+1/3-1/4+1/5 ... + 1/99-1/100.

Related Keywords:
Related Article

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• Sales Support

1 on 1 presale consultation

• After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.