Implemented in C: Calculate 1/1-1/2+1/3-1/4+1/5 ... + 1/99-1/100 value.

Source: Internet
Author: User
Tags pow

To get this topic, we will first think of using loops to complete.

But not every operator is a "+" sign.

Therefore, we are here to use (-1) of the I-side to do "+" "-" number control.

The loop variable i is then treated as the denominator.

Here we have the idea of the loop body is basically OK.

It is important to note that the calculation results here are expressed in decimals, so it is not possible to define variables with int integers.

The code is as follows:

#include <stdio.h>#include<math.h>intMain () {inti; floatsum=0.0, temp=0.0;  for(i =1; I <= -; i++) {Temp= POW (-1, i +1); Sum= Sum + temp *1/i; } printf ("sum is%f\n", sum); System ("Pause"); return 0;}

A function pow is used in the code,

This function is used to represent the function of the secondary side, so it is necessary to refer to the header file MATH.H.

Of course, we do not use the POW function to complete the programming.

In the loop body, we can define an auxiliary variable flag to make flag=1.

In the loop body, we just need to make flag=-flag at the end,

This allows the flag to be transformed between 1 and 1 to complete programming.

The code is as follows:

#include <stdio.h>intMain () {intI, flag =1; floatsum =0.0;  for(i =1; I <= -; i++) {sum= Sum + flag* (1.0/i); Flag= -Flag; } printf ("sum is%f\n", sum); System ("Pause"); return 0;}

Finally, attach the result of the program running:

Implemented in C: Calculate 1/1-1/2+1/3-1/4+1/5 ... + 1/99-1/100 value.

Contact Us

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.