c++使用graphics绘制指定数量随机位置的矩形,并在矩形里填充指定数量的圆形
时间: 2024-02-05 09:13:32 浏览: 15
下面是一个使用graphics绘制指定数量随机位置的矩形,并在矩形里填充指定数量的圆形的示例代码:
```c++
#include <graphics.h>
#include <ctime>
#include <cstdlib>
int main() {
int n_rectangles = 10; // 矩形数量
int n_circles = 5; // 圆形数量
int radius = 20; // 圆的半径
srand(time(NULL)); // 设置随机数种子
initwindow(640, 480); // 初始化窗口
// 绘制矩形和填充圆形
for (int i = 0; i < n_rectangles; i++) {
int x = rand() % (getmaxx() - 100) + 50; // 随机生成矩形左上角x坐标
int y = rand() % (getmaxy() - 100) + 50; // 随机生成矩形左上角y坐标
int width = rand() % 100 + 50; // 随机生成矩形宽度
int height = rand() % 100 + 50; // 随机生成矩形高度
rectangle(x, y, x + width, y + height); // 绘制矩形
for (int j = 0; j < n_circles; j++) {
int cx = rand() % width + x; // 随机生成圆心x坐标
int cy = rand() % height + y; // 随机生成圆心y坐标
circle(cx, cy, radius); // 绘制圆形
}
}
getch(); // 等待用户输入
closegraph(); // 关闭图形窗口
return 0;
}
```
这个示例程序使用 `rand()` 函数生成随机数来确定矩形和圆形的位置和大小。在绘制每个矩形时,它还会在矩形内部随机生成指定数量的圆形,并用 `circle()` 函数绘制它们。
请注意,这个示例代码使用了 `graphics.h` 这个库,这个库通常在 Windows 平台上使用。如果你正在使用其他平台,则可能需要使用其他的绘图库来实现类似的功能。