以下是一个C语言实现跳动爱心的源代码:
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #define WIDTH 80 #define HEIGHT 30 void drawHeart(int x, int y); void clearScreen(); void sleep(int milliseconds); int main() { int x = WIDTH / 2, y = HEIGHT / 2; int dx = 1, dy = 1; while (1) { clearScreen(); drawHeart(x, y); x += dx; y += dy; if (x <= 0 || x >= WIDTH) { dx = -dx; } if (y <= 0 || y >= HEIGHT) { dy = -dy; } sleep(50); } return 0; } void drawHeart(int x, int y) { double a, b, distance; for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { a = (double)(j - x) / 5; b = (double)(i - y) / -2; distance = sqrt(a * a + b * b); if (distance < 1.5) { printf("*"); } else { printf(" "); } } printf("\n"); } } void clearScreen() { system("cls"); } void sleep(int milliseconds) { clock_t start = clock(); while ((clock() - start) * 1000 / CLOCKS_PER_SEC < milliseconds); }
程序实现的功能是:屏幕上出现一个跳动的爱心图案,爱心图案会在屏幕内来回移动。程序中采用了Windows下的system("cls")
函数来清屏,因此程序只能在Windows下运行。如果要在其他操作系统下运行,需要修改清屏函数。
评论