最近在学习数组,前几周已经把数据类型和程序流程结构学习完毕
这些是在vs上完成的代码文件,主要是本周学习的内容
一、while循环
这是一个猜数字的案例
案例描述:系统随机生成一个1到100之间的数字,玩家进行猜测,如果猜错,提示玩家数字过大或者过小,如果猜对则恭喜玩家胜利,并退出游戏。
#include<iostream>
using namespace std;
int main()
{
//添加随机数种子 利用;当前系统时间生成随机数,防止每次随机数都一样
srand((unsigned int)time(NULL));
int num = rand() % 100 + 1;
//cout << num << endl;
int val = 0;//玩家输入的数据
while (val = num)
{
cin >> val;
if (val > num)
{
cout << "猜测过大,请重新猜测" << endl;
}
else if (val < num)
{
cout << "猜测过小,请重新猜测" << endl;
}
else
{
cout << "恭喜猜测正确" << endl;
break;//break,可以利用该关键字来退出循环
}
}
return 0;
}
二、do...while循环
这个是一个关于水仙花数的案例
案例描述:水仙花数是指一个3位数,它的每个个位上的数字的3次幂之和等于它本身
例如:1^3+5^3+3^3=153
//do...while循环案例:水仙花数
#include<iostream>
using namespace std;
int main()
{
int num = 100;
do
{
int a = 0;
int b = 0;
int c = 0;
a = num % 10;
b = num % 100 / 10;
c = num / 100;
if (a * a * a + b * b * b + c * c * c == num)
{
cout << num << endl;
}
num++;
} while (num < 1000);
system("pause");
return 0;
}
三、for循环
这是一个敲桌子的案例
案例描述:从1开始数到数字100,如果数字个位含有7,或者数字十位含有7,或者该数字是7的倍数,我们打印敲桌子,其余数字直接打印输出。
#include<iostream>
using namespace std;
int main()
{
for (int n = 1; n <= 100; n++)
{
if (n % 10 == 7 || (n / 10) % 10 == 7 || n % 7 == 0)
cout << "敲桌子" << endl;
else
cout << n << endl;
}
return 0;
}
四、嵌套循环
#include<iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 9; i++)
{
for (int j = 1; j <= i; j++)
{
cout << j << " * " << i << " = " << j * i << " ";
}
cout << endl;
}
system("pause");
return 0;
}
案例描述:利用嵌套循环,实现九九乘法表
#include<iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 9; i++)
{
for (int j = 1; j <= i; j++)
{
cout << j << "*" << i << "=" << j * i << " ";
}
cout << endl;
}
system("pause");
return 0;
}
五、数组
所谓数组就是一个集合,里面存放了相同类型的数据元素
特点1:数组中的每个元素都是相同的数据类型
特点2:数组里由连续的内存位置组成