用c++编写动态爱心
时间: 2023-07-01 20:08:27 浏览: 76
以下是用C++编写动态爱心的示例代码:
```c++
#include <iostream>
#include <cmath>
#include <Windows.h>
using namespace std;
void setColor(int color) {
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
}
int main() {
int width = 80; // 窗口宽度
int height = 30; // 窗口高度
int centerX = width / 2; // 窗口中心点x坐标
int centerY = height / 2; // 窗口中心点y坐标
int r = min(centerX, centerY) - 4; // 爱心半径
double x, y, distance;
while (true) {
system("cls"); // 清空控制台屏幕
for (int i = 0; i < height; i++) { // 遍历每一行
for (int j = 0; j < width; j++) { // 遍历每一列
x = j - centerX;
y = centerY - i;
distance = sqrt(x * x + y * y);
if (distance < r) { // 点在爱心内部
if (i >= centerY) { // 下半部分
if (j < centerX) {
setColor(FOREGROUND_RED | FOREGROUND_INTENSITY); // 红色
cout << "♥";
} else {
setColor(FOREGROUND_BLUE | FOREGROUND_INTENSITY); // 蓝色
cout << "♥";
}
} else { // 上半部分
setColor(FOREGROUND_GREEN | FOREGROUND_INTENSITY); // 绿色
cout << "♥";
}
} else {
cout << " "; // 点在爱心外部
}
}
cout << endl; // 换行
}
Sleep(200); // 延时,使动态效果更明显
}
return 0;
}
```
这段代码会在控制台窗口中实现动态爱心效果。其中,使用了数学公式求解点与圆心之间的距离,来判断点是否在爱心内部。如果点在爱心内部,则根据点的位置确定爱心的颜色。最后,使用`Sleep`函数来延时,使动态效果更明显。