C++ 代码绘制爱心 - 图形库和字符画两种方法
以下是一个简单的爱心 C++ 代码,使用了图形库 graphics.h 来绘制:
#include <graphics.h>
int main()
{
initwindow(640, 480, 'Love Heart'); // 创建窗口
setcolor(RED); // 设置画笔颜色为红色
setfillstyle(SOLID_FILL, RED); // 设置填充模式为实心红色
// 绘制左侧心形
int x1 = 200, y1 = 200, x2 = 300, y2 = 300;
arc(x1, y1, 0, 180, 80);
arc(x2, y1, 0, 180, 80);
line(x1 - 80, y1 + 40, x2 + 80, y1 + 40);
floodfill(x1 + 1, y1 + 1, RED);
// 绘制右侧心形
x1 = 340, y1 = 200, x2 = 440, y2 = 300;
arc(x1, y1, 0, 180, 80);
arc(x2, y1, 0, 180, 80);
line(x1 - 80, y1 + 40, x2 + 80, y1 + 40);
floodfill(x1 + 1, y1 + 1, RED);
while (!kbhit()) // 等待按键退出
{
delay(100);
}
closegraph(); // 关闭窗口
return 0;
}
该代码使用了 graphics.h 图形库,需要在编译时链接 winbgim 库。如果你使用的是 Code::Blocks 等 IDE,可以参考以下链接进行设置:
- 配置 Code::Blocks 开发环境:https://blog.csdn.net/wanzhen4330/article/details/103369869
- 在 Code::Blocks 中使用图形库:https://blog.csdn.net/u010781856/article/details/86580469
如果你不想使用图形库,也可以使用字符画的方式来绘制爱心,例如:
#include <iostream>
#include <string>
using namespace std;
int main()
{
const string HEART =
' * * \n'
' *** *** \n'
'********* \n'
' ******* \n'
' ***** \n'
' *** \n'
' * \n';
cout << HEART;
return 0;
}
该代码使用字符串常量来表示爱心的形状,然后使用 cout 输出到控制台。输出结果如下:
* *
*** ***
*********
*******
*****
***
*
原文地址: https://www.cveoy.top/t/topic/oflG 著作权归作者所有。请勿转载和采集!