C language study notes while statement

Introducing an example: pai approximation to calculate Pi. Given formula, calculated up to the previous 100.

With a for statement:

#include <stdio.h>
#include <math.h>
int main ()
{
	double sum =0,pi,c;
	int n;
	for (n=1;n<=100;n++)	
	{
		c = pow(-1,n+1)/(2*n-1);
		sum = sum + c ;
	}
	pi = 4 * sum;
	printf("pi=%lf\n",pi);
}

With whlie statement:

#include <stdio.h>
#include <math.h>
int main ()
{
	double sum = 0,pi,c=1,s=1;
	int n =1 ; 
	while(fabs(c)>=1e-6)	
	{
		sum = sum + c ;
		s=-s;
		n++;
		c = s/(2*n-1);
	}
	pi = 4 * sum;
	printf("pi=%lf\n",pi);
} 

while statement - "When type"

whlie (条件表达式)
	循环体

Do not ignore their own codes knock this one step will really find a lot of problems

Look at this code, using the while statement 1 + ... 100;

#include <stdio.h>
int main ()
{
	int sum =0,i=1;
	while(i<=100)
	{
		sum = sum + i;
		i=i+1;
	}
	printf("sum=%d\n",sum);
}

while statements and for statements expressed cycle, cycle times are generally suitable for use statement for an uncertain number of cycles with whlie statement.

Thank you see here! let's work hard together! see u tomorrow!

Published 20 original articles · won praise 27 · views 20000 +

Guess you like

Origin blog.csdn.net/Lemonliyi/article/details/105106780