C++ 跳转语句/break/continue/goto语句
2026/6/7 15:32:37 网站建设 项目流程

本节课涉及到的所有C++相关的代码,大家可以自行建立项目库练习

A1.break语句

作用:跳出选择结构或者循环结构

break使用的时机:

  • 出现在switch条件语句中,作用是终止case并跳出switch
  • 出现在循环语句中,作用是跳出当前的循环语句
  • 出现在嵌套循环中,跳出最近的内层循环语句

case1: 出现在switch条件语句中

#include<iostream> using namespace std; int main(){ cout << "植物大战僵尸的游戏模式:" << endl; cout << "1、生存模式" << endl; cout << "2、挑战模式" << endl; cout << "3、通关模式" << endl; int num = 0; cin >> num; switch (num) { case 1: cout << "较容易通关" << endl; break; case 2: cout << "较难通关" << endl; break; case 3: cout << "容易通关" << endl; break; default: break; } system("pause"); return 0; }

case2:出现在循环语句中

#include<iostream> using namespace std; int main(){ for (int j = 1; j <= 7; ++j) { if (j == 4) { break; } cout << j << endl; } system("pause"); return 0; }

case3:出现在嵌套循环语句中

#include<iostream> using namespace std; int main(){ for (int i = 1; i <= 7; i++) { for (int j = 1; j <= 9; j++) { if (j == 5) { break; } cout << "%" ; } cout << endl; } system("pause"); return 0; }

A2.continue语句

作用:在循环语句中,跳过本次循环中余下尚未执行的语句,继续执行下一次循环

#include<iostream> using namespace std; int main(){ for (int i = 0; i <= 50; i++) { //输出奇数 if (i % 2 == 0) { continue; } cout << i << endl; } system("pause"); return 0; }

A3.goto语句

作用:无条件跳转语句

语法:goto 标记;//如果标记的名称存在, 执行到goto语句时,就会跳转到标记的位置

#include <iostream> using namespace std; int main(){ cout << "1" << endl; cout << "2" << endl; goto FLAG; cout << "3" << endl; FLAG: cout << "4" << endl; system("pause"); return 0; }

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询