入门案例之随机数选人小程序
- 编译环境:vs2019
- 注意事项:为了使用outtextxy()函数,需要将项目 ‘属性’ ,‘高级’中的‘字符集’修改为‘使用多字节字符集’,否则会报错。
- 使用到的easyx库函数:settextstyle()、settextcolor()、outtextxy()
- 其他函数:srand()、time()、rand()、BeginBatchDraw()、exit()、FlushBatchDraw()、EndBatchDraw()。
1.种下随机数种子:
int Ran_Num()
{
srand((unsigned int)time(NULL));
int randNum = (rand() % 90 + 10);
return randNum;
}
- srand()函数作用是设置随机数范围;
- time()函数作用是获取时间戳;
- rand()函数产生随机数;
- rand()函数范围公式:rand%x+a,产生随机数范围 [0 + a,x - 1 + a ];
- 所以产生随机数的范围为:10 ~ 99
2.重写outtextxy()函数:
void outtext_int(int x,int y,int data)
{
char str[20] = "";
sprintf_s(str, 20, "%d", data);
settextstyle(100, 0, "");
settextcolor(RGB(255, 0, 128));
outtextxy(x, y, str);
}
- sprintf_s()函数的作用是:将字符串格式化输出;(若需深入了解可自己搜索)
画一个简单的界面:
void draw_Menu()
{
initgraph(800, 600, 0);
settextstyle(40, 0, "");
settextcolor(RGB(255, 255, 255));
outtextxy(300, 100, "随机选人:");
outtextxy(280, 500, "谁会是天选之子?");
}
3.处理按键:
if (GetAsyncKeyState(VK_RETURN))
{
outtextxy(310, 150, " ");//处理三个问号
outtext_int(310, 150, Ran_Num());
FlushBatchDraw();
FlushBatchDraw();
}
if (GetAsyncKeyState(VK_ESCAPE))
{
FlushBatchDraw();
exit(OVERFLOW);
}
- exit()函数是退出程序;(若需深入了解可自己搜索)
- GetAsyncKeyState()函数是接收按键函数;(若需深入了解可自己搜索)
4.包含头文件
#include <iostream>
#include <time.h>
#include <easyx.h>
#include <stdlib.h>
最后附上运行截图:
感谢您的阅读;如有不足还请多多指教。