目录
while循环
#include <iostream>
using namespace std;
int main(){
int num = 0;
// 一定要避免死循环的出现
while (num < 10)
{
// cout << num << endl;
// num++;
cout << num++ << endl; //这个和上面的是一样的
}
return 0;
}
输出:
0
1
2
3
4
5
6
7
8
9
do…while循环语句
与while的区别在于do…while会先执行一次循环,再判断循环条件
#include <iostream>
using namespace std;
int main(){
int num = 0;
do
{
cout << num << endl;
num++;
} while (num < 10);
return 0;
}
水仙花数
#include <iostream>
using namespace std;
int main(){
int num = 100;
int hundred = 0;
int ten = 0;
int one = 0;
do
{
hundred = num / 100;
ten = (num - hundred*100) / 10;
one = (num - hundred*100 - ten*10);
if (hundred*hundred*hundred + ten*ten*ten + one*one*one == num)
{
cout << num << endl;
}
num++;
} while (num < 1000);
return 0;
}
输出:
153
370
371
407
for循环语句
#include <iostream>
using namespace std;
int main(){
for (int i = 0;i < 10;i++)
{
cout << i << endl;
}
return 0;
}
例子:找7(个位或十位有7或者是7的倍数)
#include <iostream>
using namespace std;
int main(){
int hundred = 0;
int ten = 0;
int one = 0;
for (int num = 0;num < 101;num++)
{
hundred = num / 100;
ten = (num - hundred*100) / 10;
one = (num - hundred*100 - ten*10);
if (one==7||ten==7||num % 7==0) //这里只有一条|的话可以输出但是会有警告
{
cout << num << endl;
}
}
return 0;
}
嵌套循环
#include <iostream>
using namespace std;
int main(){
for (int i = 0 ; i < 10 ; i++)
{
for (int j = 0 ; j < 10 ; j++)
{
cout << "* ";
// cout << "* " << endl; 注意:不能加后面的这个,否则会一条输出不会一行
}
cout << endl;
}
return 0;
}
输出:
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
九九乘法表
#include <iostream>
using namespace std;
int main(){
for (int i = 1 ; i < 10 ; i++)
{
for (int j = 1 ; j < 10 ; j++)
{
if (j < i+1)
{
cout << j << "×" << i << " ";
}
}
cout << endl;
}
return 0;
}
输出:
1×1
1×2 2×2
1×3 2×3 3×3
1×4 2×4 3×4 4×4
1×5 2×5 3×5 4×5 5×5
1×6 2×6 3×6 4×6 5×6 6×6
1×7 2×7 3×7 4×7 5×7 6×7 7×7
1×8 2×8 3×8 4×8 5×8 6×8 7×8 8×8
1×9 2×9 3×9 4×9 5×9 6×9 7×9 8×9 9×9