1.while循环小练习
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
//添加随机数种子,作用:利用当前系统时间生成随机数,防止每次生成随机数相同
srand((unsigned int)time(NULL)); //包含头文件ctime
int i = rand() % 100 + 1; //生成一个0-99+1的随机数
int value;
while (1)
{
cout << "青菜一个数字" << endl;
cin >> value;
if (value > i)
{
cout << "猜大了" << endl;
}
else if (value < i)
{
cout << "猜小了" << endl;
}
else
{
cout << "恭喜你猜对了" << endl;
break; //利用break关键字退出循环
}
}
system("pause");
return 0;
}
2.do…while循环语句
#include <iostream>
using namespace std;
int main()
{
//用do...while循坏输入0-9
int num = 0;
//do...while和while的区别是do..while会先执行一次循环语句
do
{
cout << num << endl;
num++;
} while (num < 10);
system("pause");
return 0;
}
3.水仙花数案例
水仙花数是指一个三位数,它的每一位的数字的3次幂之和等于它本身
#include <iostream>
using namespace std;
int main()
{
//1.打印所有三位数
int num = 100;
do
{
int a = num % 10; //定义个位
int b = num / 10 % 10; //定义十位
int c = num / 100; //定义百位
//如果是水仙花数才打印
if (num == (a*a*a)+(b*b*b)+(c*c*c))
{
cout << num << endl;
}
num++;
} while (num < 1000);
system("pause");
return 0;
}
4.for循环
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i < 10; i++)
{
cout << i << endl;
}
system("pause");
return 0;
}
5.敲桌子游戏
0-100中输出7的倍数和各位十位有7的数字
#include <iostream>
using namespace std;
int main()
{
//1.先输出1-100的数字
for (int i = 1; i <= 100; i++)
{
if (i % 7 ==0 || i % 10 == 7 || i / 10 == 7)
{
cout << "敲桌子" << endl;
}
else
{
cout << i << endl;
}
}
system("pause");
return 0;
}
6.嵌套循环(打印一个10*10的星号矩阵)
#include <iostream>
using namespace std;
int main()
{
//外层循环(外层执行一次,内层执行一个周期)
for (int j = 0; j < 10; j++)
{
//内层循环
for (int i = 0; i < 10; i++)
{
cout << "* ";
}
cout << endl;
}
system("pause");
return 0;
}
7.九九乘法表
#include<iostream>
using namespace std;
int main()
{
int i;
int j;
for (i = 1; i <= 9; i++)
{
//cout << i << endl;
for (j = 1; j <= i; j++)
{
cout << j << "*" << i << "=" << i * j << " ";
}
cout << endl;
}
system("pause");
return 0;
}
8.跳转语句
(1)break:在switch中用于用于终止case并跳出switch,在循环语句中用于跳出循环,在嵌套循环中跳出最近的内层循环。
(2)continue:执行到该语句时就不在向下执行继续执行本次循环,直到循环结束为止。
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i < 100; i++)
{
if (i % 2 == 0)
{
//continue; //可赛选条件,执行到此就不再向下执行,执行下一次循环
break; //而break是直接退出最近的循环
}
cout << i << endl;
}
system("pause");
return 0;
}
结果:用continue时结果输出的是0-100的偶数
用break是没有任何输出
9.goto语句
作用:可以无条件跳转语句(如果标记的名称存在,执行到goto语句时,会跳转到标记的位置)
#include <iostream>
using namespace std;
int main()
{
cout << "1xxxxx" << endl;
cout << "2xxxx" << endl;
goto FLAG;
cout << "3xxxx" << endl;
cout << "4xxxxxx" << endl;
FLAG:
cout << "5xxxxxxxxx" << endl;
system("pause");
return 0;
}
执行结果:3、4没有打印