(C language) Calculate the value of 1/1-1/2+1/3-1/4+1/5 ... + 1/99 - 1/100 (basic written test questions)

Calculate the value of 1/1-1/2+1/3-1/4+1/5 ... + 1/99 - 1/100

I haven't been on CSDN for several days in the middle, and I am still learning. Today, I am full of blood and resurrected. Let's write a few small practice codes, learn C/C++ again, and start attacking the master's thesis at the same time. mutual encouragement!

The solution to this question can be divided into two parts and then summed, that is, sum=sum1+sum2;
where sum1 is used to represent odd items
and sum2 is used to represent even items
Note: because they are all fractions, so for sum, sum1 and When sum2 is defined, it should be of type float.
The code is:

#include<stdio.h>
#include<stdlib.h>
int main()
{
    
    
	int i, j;
	float sum = 0;
	float sum1 = 0;
	float sum2 = 0;
	for (i = 1; i < 100; i += 2)
		sum1 = sum1 + 1.0 / i;
	for (j = 2; j <= 100; j +=2)
		sum2 = sum2 - 1.0 / j;
	sum = sum1 + sum2;
	printf("%f\n", sum);
	system("pause");
	return 0;
}

The output is:
insert image description here

Guess you like

Origin blog.csdn.net/qq_42433334/article/details/102912922