心形曲線方程:(x^2 + y^2 - 1)^3 - x^2 y^3 <= 0,離散化到字符網格判斷每個位置是否在心形內。
#include
#include
int main() {
// x: -1.5 到 1.5,步長 0.05
// y: 1.5 到 -1.5,步長 0.1 (字符高寬比約2:1)
for (float y = 1.5f; y >= -1.5f; y -= 0.1f) {
for (float x = -1.5f; x <= 1.5f; x += 0.05f) {
float x2 = x * x, y2 = y * y;
float val = (x2 + y2 - 1) * (x2 + y2 - 1) * (x2 + y2 - 1) - x2 * y2 * y;
putchar(val <= 0.0f ? '♥' : ' '); // 或用 '*' '#'
}
putchar('\n');
}
return 0;
}
// 利用對稱性,僅計算上半部分
char heart[] = {
" *** *** ",
" ***** ***** ",
" *********** ",
" ********* ",
" ******* ",
" ***** ",
" *** ",
" * "
};
// 直接打印數組
// 獲取控制台寬高 (Windows API)
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
int consoleWidth = csbi.srWindow.Right - csbi.srWindow.Left + 1;
int consoleHeight = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
// 計算心形寬高行數,打印前輸出相應空行和左側空格
♥♥♥ ♥♥♥
♥♥♥♥♥♥♥♥♥♥♥♥♥
♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
♥♥♥♥♥♥♥♥♥♥♥♥♥
♥♥♥♥♥♥♥♥♥♥♥
♥♥♥♥♥♥♥♥♥
♥♥♥♥♥♥♥
♥♥♥♥♥
♥♥♥
♥