1. while循环
- 作用:满足循环条件,执行循环语句
- 语法:while(循环条件){循环语句} // 循环条件为真,就执行循环语句
#include<iostream>
using namespace std;
int main()
{
int num = 0;
while (num < 10)
{
cout << num << endl;
num++;
}
system("pause");
return 0;
}
案例:猜数字,系统随机生成一个数字,猜对结束,猜错提示过大还是过小
#include<iostream>
using namespace std;
#include<ctime>
int main()
{
srand((unsigned int)time(NULL));
int num= rand() % 100;
cout << "give your num:" << endl;
int nums = 0;
cin >> nums;
cout << "your num is:" << nums<<endl;
while (nums!=num)
{
if (nums > num)
{
cout << "your num is too big!:" << endl;
}
else
{
cout << "your num is too small!:" << endl;
}
cout << "give your num again:" << endl;
cin >> nums;
cout << "your num is:" << nums << endl;
}
system("pause");
return 0;
}
或者:
#include<iostream>
using namespace std;
#include<ctime>
int main()
{
srand((unsigned int)time(NULL));
int num= rand() % 100;
while (1)
{
cout << "give your num:" << endl;
int nums = 0;
cin >> nums;
cout << "your num is:" << nums << endl;
if (nums > num)
{
cout << "your num is too big!:" << endl;
}
else if(nums<num)
{
cout << "your num is too small!:" << endl;
}
else
{
cout << "your num is right!:" << endl;
break;
}
}
system("pause");
return 0;
}
2. do…while循环
- 作用:满足循环条件,执行循环语句
- 语法:do{循环语句} while(循环语句);
- 注意:先执行一次循环语句,再判断循环条件
#include<iostream>
using namespace std;
int main()
{
int num = 0;
do
{
cout << num << endl;
num += 1;
} while (num<10);
system("pause");
return 0;
}
案例:水仙花数,一个三位数,每个位上的数字的三次幂等于数字本身,利用do…while语句,找出3位数中的水仙花数
#include<iostream>
using namespace std;
int main()
{
int num = 100;
do
{
int gewei = num %10;
int shiwei = (num / 10)%10;
int baiwei = num / 100;
if (gewei* gewei* gewei + shiwei * shiwei * shiwei+ baiwei * baiwei * baiwei == num)
{
cout << num << endl;
}
num += 1;
} while (num < 1000);
system("pause");
return 0;
}
3. for循环
- 作用:满足循环条件,执行循环语句
- 语法:for(起始表达式;条件表达式;末尾循环体) {循环体}
- 优点:结构清晰
#include<iostream>
using namespace std;
int main()
{
for (int i = 0; i < 10; i++)
{
cout << i << endl;
}
system("pause");
return 0;
}
案例:敲桌子,从1开始到数字100,如果数字个位含7、十位含7或者该数是7的倍数,打印敲桌子,其余数字直接打印
- 个位含7:num%10==7
- 十位含7:num/10==7
- 7的倍数 :num%7==0
#include<iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 100; i++)
{
if (i%7==0 || i%10==7 || i/10==7)
{
cout << "qiao zhuo zi" << endl;
}
else
{
cout << i << endl;
}
}
system("pause");
return 0;
}
4. 嵌套循环
案例1:打印8x9矩阵的*
#include<iostream>
using namespace std;
int main()
{
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 9; j++)
{
cout << "* " ;
}
cout << endl;
}
system("pause");
return 0;
}
案例2:乘法口诀表
#include<iostream>
using namespace std;
int main()
{
for (int i = 1; i < 10; i++)
{
for (int j = 1; j <= i; j++)
{
cout << j<<"*"<<i<<"=" << j * i << "\t";
}
cout << endl;
}
system("pause");
return 0;
}

|