一、while循环语句
#include <iostream> using namespace std; #include<ctime> int main() { //打印0-9 int num = 0; while (num < 10) { cout << num << endl; num++; } //猜数字 //生成随机数 srand((unsigned int) time(NULL)); int num2 = rand() % 100 + 1; // 玩家猜测 while (true) { int val = 0; cout << "请输入猜测的数字:" << endl; cin >> val; if (num2 > val) { cout << "猜小了" << endl; } else if (val > num2) { cout << "猜大了" << endl; } else { cout << "恭喜你,猜对了。" << endl; break; } } return 0; }
0 1 2 3 4 5 6 7 8 9 请输入猜测的数字: 25 猜小了 请输入猜测的数字: 75 猜大了 请输入猜测的数字: 50 猜大了 请输入猜测的数字: 42 恭喜你,猜对了。
二、do...while循环语句
#include <iostream> using namespace std; int main() { //do while输出0-9 先执行,后判断 int num = 0; do { cout << num << endl; num++; } while (num < 10); return 0; }
0 1 2 3 4 5 6 7 8 9
#include <iostream> using namespace std; int main() { int num = 100; do { // 获取百位数 int num1 = num / 100; // 获取十位数 int num2 = (num / 10) % 10; // 获取个位数 int mum3 = num % 10; // 水仙花数判断 if (num1 * num1 * num1 + num2 * num2 * num2 + mum3 * mum3 * mum3 == num) { cout << num << endl; } num++; } while (num < 1000); return 0; }
153 370 371 407
三、for循环语句
#include <iostream> using namespace std; int main() { // for循环 for (int i = 0; i < 10; ++i) { cout << i << endl; } // 敲桌子 如果个位或十位包含7 或者7的倍数 打印@_@ 否则打印数字 cout << "-------------------------" << endl; for (int i = 1; i <= 100; ++i) { if (i % 7 == 0 || i % 10 == 7 || i / 10 == 7) { cout << "@_@" << endl; } else { cout << i << endl; } } return 0; }
0 1 2 3 4 5 6 7 8 9 ------------------------- 1 2 3 4 5 6 @_@ 8 9 10 11 12 13 @_@ 15 16 @_@ 18 19 20 @_@ 22 23 24 25 26 @_@ @_@ 29 30 31 32 33 34 @_@ 36 @_@ 38 39 40 41 @_@ 43 44 45 46 @_@ 48 @_@ 50 51 52 53 54 55 @_@ @_@ 58 59 60 61 62 @_@ 64 65 66 @_@ 68 69 @_@ @_@ @_@ @_@ @_@ @_@ @_@ @_@ @_@ @_@ 80 81 82 83 @_@ 85 86 @_@ 88 89 90 @_@ 92 93 94 95 96 @_@ @_@ 99 100
四、嵌套循环
#include <iostream> using namespace std; int main() { // 嵌套循环 for (int i = 0; i < 10; ++i) { for (int j = 0; j < 10; ++j) { cout << "*"; } cout << endl; } cout << endl; for (int i = 1; i < 10; ++i) { for (int j = 1; j <= i; ++j) { cout << i << "*" << j << "=" << i * j << " "; } cout << endl; } return 0; }
********** ********** ********** ********** ********** ********** ********** ********** ********** ********** 1*1=1 2*1=2 2*2=4 3*1=3 3*2=6 3*3=9 4*1=4 4*2=8 4*3=12 4*4=16 5*1=5 5*2=10 5*3=15 5*4=20 5*5=25 6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36 7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49 8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64 9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81
五、跳转语句
#include <iostream> using namespace std; int main() { // break 终端循环 for (int i = 0; i < 10; ++i) { if (i == 5) { break; } cout << i << " "; } cout << endl; //continue 跳过本次循环 for (int i = 0; i < 10; ++i) { if (i == 5) { continue; } cout << i << " "; } cout << endl; // goto 跳转到标记位置 cout << "1" << endl; goto FLAG; cout << "2" << endl; cout << "3" << endl; cout << "4" << endl; FLAG: cout << "5" << endl; return 0; }
0 1 2 3 4 0 1 2 3 4 6 7 8 9 1 5