## 第三节循环语句
### 1.基础知识
:while do while for
if 是判断一次执行后面的语句,while是每次成立执行循环语句中的语句
~~~c++
int i=0;
if(i<10)
{
cout<<i<endl;
i++;
}
while(i<10)
{
cout<<i<endl;
i++;
}
第二个输出
0
第二个输出
0
1
2
……
9
~~~
### 2.do while while
do while循环先执行再判断。while判断执行
while(cin>>n,n)意思是电脑让用户读入n,并且循环n次。如果将cin>>n放到外面,可能会做超时处理。
例如:从1加到10
~~~c++
int main()
{
int s=0,r=0;
while(j<=10)
{
r=r+j;j++;
}
cout << r << endl;
int i=1;
do{
s=s+i;i++;
}while(i<=10);
cout <<s<<endl;
return 0;
}
~~~
两种输出一样都是55
### 3.for
for(int 语句;条件语句;表达式)
例:
~~~c++
int main()
{
for (int i=1;i<=10;i++)
{
cout << i <<endl;
}
return 0;
}输出1
2
……
10
~~~
多重循环
画一个菱形,用曼哈顿距离求解
<img src="C:\Users\明月无暇—城池喑哑\Desktop\C++\语法基础\语法基础.assets\image-20221111173003197.png" alt="image-20221111173003197" style="zoom:33%;" />
~~~c++
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int n;
cin >> n;
int sx = n / 2, sy = n / 2;
for (int i = 0; i < n ; i ++ )
{
for (int j = 0; j < n; j ++ )
{
if ( abs(sx - i) + abs(sy - j) <= n / 2 ) cout << "*";
else cout << " ";
}
cout << endl;
}
return 0;
}
~~~
<img src="C:\Users\明月无暇—城池喑哑\Desktop\C++\语法基础\语法基础.assets\image-20221111174353767.png" alt="image-20221111174353767" style="zoom:33%;" />
1.输入三个数,a,b,c 并将 a,b,c 三个数降序排列
~~~c++
if (A<B)
{ double T;
T=A;
A=B;
B=T;
}//使A>b
if(A<C)
{
double t;
t=A;
A=C;
C=t;
}//使A>c
if(C>B)
{
double t;
t=B;
B=C;
C=t;
}//使b>c
~~~
2.例题
1.
<img src="C:\Users\明月无暇—城池喑哑\Desktop\C++\语法基础\语法基础.assets\image-20221111092214622.png" alt="image-20221111092214622" style="zoom:50%;" />
~~~c++
#include <cstdio>
#include <iostream>
using namespace std;
int main()
{
int n=0;
for (int i=0;i<6;i++)//定义一个循环,使其输入6次
{
double x;
cin >> x;
if(x>0)
n++;
}
cout << n << " positive numbers" << endl;
return 0;
}
~~~
2.1加到n的立方
<img src="C:\Users\明月无暇—城池喑哑\Desktop\C++\语法基础\语法基础.assets\image-20221111094933982.png" alt="image-20221111094933982" style="zoom: 50%;" />
3.斐波那契数列
![image-20221111153453225](C:\Users\明月无暇—城池喑哑\Desktop\C++\语法基础\语法基础.assets\image-20221111153453225.png)
~~~C++
#include<cstdio>
#include<iostream>
using namespace std;
int main()
{
int a,b;
a=0;
b=1;
int n;
cin>>n;
int i=0;
printf("%d ",a);
while(i<n-1)
{
int c=a+b;
a=b;
b=c;
i++;
printf("%d ",a);
}
return 0;
}
~~~
标签:cout,int,c++,++,while,循环,include From: https://www.cnblogs.com/Cathy-cat/p/16882462.html