1e-6){sum += (1.0 / i) * j;i+=2; j = -j; }"."/> 1e-6){sum += (1.0 / i) * j;i+=2; j = -j; }".">

Home  >  Article  >  Backend Development  >  c language while loop example

c language while loop example

L
LOriginal
2020-05-30 18:01:468333browse

c language while loop example

C language while loop example

The execution sequence of the while loop is very simple, its format is:

while ( Expression)
{
Statement;
}

When the expression is true, the following statement is executed; after the statement is executed, it is judged whether the expression is true. If it is true, Execute the following statement again; then determine whether the expression is true... This loop continues until the expression is false and breaks out of the loop. This is the execution sequence of while.
Note that when programming for beginners, no matter how many lines there are in the execution statements following if, else, for, while, and do, "{}" must be added even if there is only one line. It is particularly important to develop good programming habits.
Write a program below to implement this function: calculate the value of (1-1/3 1/5-1/7 1/9-1/11…)*4.

# include <stdio.h>
int main(void){
int i = 1;int j = 1;
double sum = 0;  //结果肯定是小数, 所以要定义成double或float型
while (1.0/i > 1e-6)  /*当1/i小于10的-6次方时停止循环。这个循环条件是自己定的, 定得越小最后的结果就越精确。注意1一定要写成小数的形式即1.0*/
{
sum += (1.0 / i) * j;
i+=2;j = -j;  //实现正负交替
}
sum *=4;
printf("sum = %lf\n", sum);  //double是%lf, 取6位小数是%.6return 0;
}

The output result is:
sum = 3.141591

Recommended learning: c language video tutorial

The above is the detailed content of c language while loop example. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn