4.2 循环结构
语法: while(循环条件){循环语句}
#includeusing namespace std; int main(){ int num = 0; cout << num << endl; while(num < 10) { num++; cout << num << endl; } system("pause"); return 0; }
while循环练习案例:猜数字
案例描述:系统随机生成一个1到100之间的数字,玩家进行猜测,如果猜错,提示玩家过大或过小,如果猜对恭喜玩家胜利,并且退出游戏。
#includeusing namespace std; //time系统时间头文件包含 #include int main(){ //添加随机数种子,利用当前系统时间生成随机数,防止每次随机数都一样 srand((unsigned int)time(NULL)); int num = rand()%100+1//rand()%100生成0-99随机数 cout << num < > val; while(1) { if(val > num) { cout << "猜测过大" << endl; } else if(val < num) { cout << "猜测过小" << endl; } else { cout << "恭喜您猜对了" << endl; break; } } system("pause"); return 0; }
4.2.2 do...while循环语句
语法:do{循环语句}while{循环条件};
#includeusing namespace std; //time系统时间头文件包含 int main(){ //在屏幕中输出0到9这是个数字 int num = 0; do { cout << num < 练习案例:水仙花数
案例描述:水仙花数是指一个三位数,它的每个位上的数字的三次幂之和等于它本身
例如:1^3+ 5^3+ 3^3=153
求出所有的水仙花数。
#includeusing namespace std; int main(){ //在屏幕中输出0到9这是个数字 int num = 100; do { int a = 0; int b = 0; int c = 0; a = num % 10;//获取个位 b = num / 10 % 10;//获取十位 c = num / 100 % 10;//获取百位 if(a*a*a+b*b*b+c*c*c == num) { cout << num < 4.2.3 for循环语句
语法:for{起始表达式;条件表达式;末尾循环体}{ 循环语句 }
#includeusing namespace std; int main(){ //从数字0打印到9 for( int i = 0; i < 10; i++ ) { cout << i << endl; } system("pause"); return 0; } 练习案例:敲桌子
案例描述:从1开始数到数字100,如果数字个位含有7,或该数字是7的倍数,我们打印敲桌子,其余数字直接打印输出。
#includeusing namespace std; int main(){ for( int i = 1; i <= 100; i++ ) { if ( i % 7 == 0 || i % 10 == 7 || i / 10 == 7 ) { cout << "敲桌子" << endl; } cout << i << endl; } system("pause"); return 0; } 4.2.4 嵌套循环
#includeusing namespace std; int main(){ //利用嵌套循环实现星图 for( int i = 0; i < 10; i++ ) { for( int j = 0; j < 10; j++ ) { cout << "* "; } cout << endl } system("pause"); return 0; } 乘法口诀表
#includeusing namespace std; int main(){ //乘法口诀表 for( int i = 1; i <= 9; i++ ) { cout << j << endl; for( int j = 1; j < i; j++ ) { cout << j << " * " << i << " "; } cout << endl } system("pause"); return 0; }



