C++break语句用法
目录
1、break使用
在switch语句中,break的作用是终止case语句,并跳出switch
在单个循环语句中,break作用是跳出循环语句
在嵌套循环中,break作用是跳出最近循环,并且不影响外面的循环。
2、代码演示
#include<iostream>
using namespace std;
int main() {
//break用法
//switch语句
int score = 0;
cin >> score;
switch (score)
{
case 1:
cout << "优秀"<<endl;
break;//跳出当前switch
case 2:
cout << "良" << endl;
break;
default:
cout << "及格" << endl;
break;
break;
}
//循环语句中
for (int i = 0; i < 10; i++)
{
if (i==5)
{
break;//退出循环
}
cout << i << " ";
}
cout << endl;
//嵌套循环
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
if (j==5)
{
break;//退出最近循环
}
cout << "* ";
}
cout << endl;
}
system("pause");
return 0;
}
2
良
0 1 2 3 4
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
请按任意键继续. . .