程序流程结构2
2.循环结构
3.跳转语句
2.循环结构
while(循环条件){
}
避免程序死循环
必须有跳出循环的出口
#include<iostream>
using namespace std;
int main() {
//打印0-20
int num = 0;
while (num <= 20)
{
cout << num << endl;
num++;
}
system("pause");
return 0;
}
举例:猜数字
系统生成随机数,如果猜的不对,提示猜的偏大还是偏小。直到正确猜数。
#include<iostream>
//系统时间的头文件
#include<ctime>
using namespace std;
int main() {
//添加随机数的种子,利用系统时间生成随机数,否自每次随机数都一样
//1.系统生成随机数
srand((unsigned int)time(NULL));
int num1 = rand() % 100 + 1;//rand()%100 + 1生成 0 + 1~99 + 1随机数
//cout << num1 << endl;
//2.玩家猜测
int val = 0;
while (1) {
cin >> val;
//3.判断玩家猜测
if (val > num1) {
cout << "玩家猜测过大" << endl;
}
else if(val < num1){
cout << "玩家猜测过小" << endl;
}
else {
cout << "猜对了!!!" << endl;
break;//退出当前循环
}
}
//4.猜对退出游戏,猜错提示大小,并且继续2过程
system("pause");
return 0;
}
(2)do …while循环语句
作用:满足循环条件,执行循环语句
先执行一次循环语句,再进行循环条件判断
#include<iostream>
//系统时间的头文件
using namespace std;
int main() {
int num = 0;
do
{
cout << num << endl;
num++;
} while (num <= 10);
system("pause");
return 0;
}
举例:水仙花数
#include<iostream>
using namespace std;
int main() {
int num = 100;
do {
int a = 0;
int b = 0;
int c = 0;
a = num % 10;
b = num / 10 % 10;
c = num / 100;
//cout << num << endl;
if ( a * a * a + b * b * b + c * c * c == num) {
cout << num << endl;
}
num++;
} 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;
}
举例:0-40中包含3或3的倍数
#include<iostream>
using namespace std;
int main() {
for (int i = 1; i <= 40; i++)
{
if (i % 3 == 0 || i % 10 == 3 || i / 10 == 3) {
cout << "特殊数" << endl;
}
else {
cout << i << endl;
}
}
system("pause");
return 0;
}
(4)嵌套循环
#include<iostream>
using namespace std;
int main() {
for (int i = 1; i < 10; i++)
{
for (int j = 1; j < 10; j++)
{
cout << "* " ;
}
cout << endl;
}
system("pause");
return 0;
}
3.跳转语句
(1)break语句
作用:跳出语句选择结构或循环结构
#include<iostream>
using namespace std;
int main() {
//break的使用,1.switch语句中,2.循环语句中,3.嵌套语句中
//循环语句中
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
break;
}
cout << i << endl;
}
//嵌套语句中
for (int i = 1; i < 10; i++)
{
for (int j = 1; j < 10; j++)
{
if (j == 5)
{
break;//退出内层循环
}
cout << "* ";
}
cout << endl;
}
}
(2)continue语句
作用:跳过本次循环尚未执行的程序,开始下一次循环
#include<iostream>
using namespace std;
int main() {
for (int i = 0; i < 100; i++)
{
if (i % 2 == 0)
{
continue;//执行到此就不再执行了
}
cout << i << endl;
}
}
(3)goto语句
语法:goto 标记
作用:如果标记内容存在,执行到goto语句,就会跳转到标记的位置。
#include<iostream>
using namespace std;
int main() {
cout << "1" << endl;
goto FLAG;
cout << "2" << endl;
cout << "3" << endl;
FLAG:
cout << "4" << endl;
cout << "5" << endl;
cout << "6" << endl;
}