课程要求:先复习下课本上对数组的讲解(随便一本教材都行)
[一维数组]
数组可以实现批量操作。比如,我们产生 10 个随机数,产生后先保存起来,然后输出最大的:
int n[10];
int i;
for (i=0; i<10; i++)
n[i] = rand() % 1000;
// 按生成的顺序,逆序输出
for (i=9; i>=0; i--)
printf("%d\n", n[i]);
// 找出最大的
int max = -1;
for (i=0; i<10; i++)
{
if (n[i] > max)
max = n[i];
}
printf("最大的数字是:%d\n", max);
看明白这个程序后,我们继续。
下面,我们绘制一个从屏幕上边任意位置往下落的白色点:
#include <graphics.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
void main()
{
srand( (unsigned)time(NULL) );
initgraph(640, 480);
int x = rand() % 640; // 点的 x 坐标
int y = 0; // 点的 y 坐标
while(!kbhit())
{
// 擦掉前一个点
putpixel(x, y, BLACK);
// 计算新坐标
y+=3;
if (y >= 480) break;
// 绘制新点
putpixel(x, y, WHITE);
Sleep(10);
}
closegraph();
}
现在利用数组,来产生 100 个随机下落的点。并且每个点落到底部后,就回到顶部重新往下落:
#include <graphics.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
void main()
{
srand( (unsigned)time(NULL) );
initgraph(640, 480);
// 定义点的坐标数组
int x[100]; // 点的 x 坐标
int y[100]; // 点的 y 坐标
int i;
// 初始化点的初始坐标
for (i=0; i<100; i++)
{
x[i] = rand() % 640;
[一维数组]
数组可以实现批量操作。比如,我们产生 10 个随机数,产生后先保存起来,然后输出最大的:
int n[10];
int i;
for (i=0; i<10; i++)
n[i] = rand() % 1000;
// 按生成的顺序,逆序输出
for (i=9; i>=0; i--)
printf("%d\n", n[i]);
// 找出最大的
int max = -1;
for (i=0; i<10; i++)
{
if (n[i] > max)
max = n[i];
}
printf("最大的数字是:%d\n", max);
看明白这个程序后,我们继续。
下面,我们绘制一个从屏幕上边任意位置往下落的白色点:
#include <graphics.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
void main()
{
srand( (unsigned)time(NULL) );
initgraph(640, 480);
int x = rand() % 640; // 点的 x 坐标
int y = 0; // 点的 y 坐标
while(!kbhit())
{
// 擦掉前一个点
putpixel(x, y, BLACK);
// 计算新坐标
y+=3;
if (y >= 480) break;
// 绘制新点
putpixel(x, y, WHITE);
Sleep(10);
}
closegraph();
}
现在利用数组,来产生 100 个随机下落的点。并且每个点落到底部后,就回到顶部重新往下落:
#include <graphics.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
void main()
{
srand( (unsigned)time(NULL) );
initgraph(640, 480);
// 定义点的坐标数组
int x[100]; // 点的 x 坐标
int y[100]; // 点的 y 坐标
int i;
// 初始化点的初始坐标
for (i=0; i<100; i++)
{
x[i] = rand() % 640;