C语言——爱心代码

1、爱心代码

你以为的:

#include <stdio.h>
#include <Windows.h>

int main()
{
	system("color 04");
	printf("\
                *********           *********\n\
            *****************   *****************\n\
           ****************************************\n\
         *******************************************\n\
        *********************************************\n\
        *********************************************\n\
        *********************************************\n\
        *********************************************\n\
        *********************************************\n\
        *********************************************\n\
         *******************************************\n\
          *****************************************\n\
           ****************************************\n\
            *************************************\n\
             ***********************************\n\
              *********************************\n\
                *****************************\n\
                  *************************\n\
                    *********************\n\
                       ***************\n\
                          *********\n\
                             ***");
    return 0;
}

运行结果:

实际上的:

#include <stdio.h>
#include <Windows.h>

int main()
{
	system("color 04");
	float x = 0.0f, y = 0.0f, a = 0.0f;
	for (y = 1.5f; y > -1.5f; y -= 0.1f)
	{
		for (x = -1.5f; x < 1.5f; x += 0.05f)
		{
			a = x * x + y * y - 1;
			if (a * a * a - x * x * y * y * y < 0)
			{
				printf("*");
			}
			else
			{
				printf(" ");
			}
		}
		Sleep(150);
		printf("\n");
	}
	return 0;
}

运行结果:

虽然两者输出结果一样,但是显然第二种更高级一些。

第一种的原理很好理解,那么第二种的原理是什么呢?

实际上原理是笛卡尔的爱心函数:

表达式是:

函数图像是:

我们发现函数图像的形状就是一个爱心,那么如何用代码实现呢?

我么可以发现,爱心内部的函数值是小于零的,爱心外部的函数值是大于零的。至此,逻辑已经很清晰了,我们只要在函数值大于零时和小于零时输出不同的字符,就可以使爱心显现。这里我们选择在函数值小于零(即爱心内部)时打印 * ,在函数大于零(即爱心外部)时打印Space(即空格),这样可以使爱心更明显。令a = x * x + y * y - 1,那么a * a * a - x * x * y * y * y就是函数。在a * a * a - x * x * y * y * y < 0printf("*");a * a * a - x * x * y * y * y > 0printf(" ");

然后就要模拟x、y轴,利用for循环来实现每个x、y对应的函数大于和小于零的表现,即如果某个点(x,y)对应的函数值小于零,则在这一点打印*,反之在这一点打印空格。这样就可以实现图像的显现。

但要将这些呈现在控制台上还要了解一些东西,因为在控制台上打印的一个字符并不是一个正方形,两个字符才能勉强凑成一个正方形。

所以我们要对x轴的模拟改进一下,将x轴的自增改为y轴的一半,这样才能使爱心更标准。如果我们不做此改进,运行结果就会是一个拉长两倍的爱心。

这样基本就实现了爱心图形的打印了,但还有一些小细节,在数据后面加f将数据作为float类型;可以加Sleep()函数,让我们看到打印每一行的过程;可以用system("color 04")将控制台背景改为黑色,前景改为红色。

你可以更改x和y的增量以改变图像的精细度,尽量保持x的增量是y的一半,增量尽量不要太小。

如果x或y的范围较大,或者打印的图形有错位,这是因为控制台的一些特性,需要缩放控制台,可以在程序运行的开始按住Ctrl + 鼠标滚轮,向上滚动是放大,向下滚动是缩小。

知道了这些我们还能打印更多图形。

2、圆形代码

#include <stdio.h>
#include <Windows.h>

int main()
{
	system("color 09");
	float x = 0.0f, y = 0.0f, a = 0.0f, b = 0.0f;
	for (y = 1.0f; y > -1.0f; y -= 0.05f)
	{
		for (x = -1.0f; x < 1.0f; x += 0.025f)
		{
			if (x * x + y * y < 1)
			{
				printf("*");
			}
			else
			{
				printf(" ");
			}
		}
		Sleep(150);
		printf("\n");
	}
	return 0;
}

3、椭圆代码

#include <stdio.h>
#include <Windows.h>

int main()
{
	system("color 0a");
	float x = 0.0f, y = 0.0f, a = 0.0f, b = 0.0f;
	for (y = 3.5f; y > -3.5f; y -= 0.05f)
	{
		for (x = -6.0f; x < 6.0f; x += 0.025f)
		{
			if (x * x / 32 + y * y / 8 < 1)
			{
				printf("*");
			}
			else
			{
				printf(" ");
			}
		}
		Sleep(150);
		printf("\n");
	}
	return 0;
}

在我的测试下,如果x、y的增量足够小,然后再把控制台缩放到最小尺寸,这时x与y的增量的关系最好是y = 3 * x。实际上不同的缩放程度会导致图形的不同程度的变形。

#include <stdio.h>
#include <Windows.h>

int main()
{
	system("color 0a");
	float x = 0.0f, y = 0.0f, a = 0.0f, b = 0.0f;
	for (y = 3.5f; y > -3.5f; y -= 0.075f)
	{
		for (x = -6.0f; x < 6.0f; x += 0.025f)
		{
			if (x * x / 32 + y * y / 8 < 1)
			{
				printf("*");
			}
			else
			{
				printf(" ");
			}
		}
		Sleep(150);
		printf("\n");
	}
	return 0;
}

这时的椭圆图像与函数图像更吻合。

下面的正方形代码里也会解释。

4、正方形代码

有多种方法实现

可以模拟为打印坐标轴的一个范围

#include <stdio.h>
#include <Windows.h>

int main()
{
	system("color 0a");
	float x = 0.0f, y = 0.0f, a = 0.0f, b = 0.0f;
	for (y = 3.5f; y > -3.5f; y -= 0.1f)
	{
		for (x = -6.0f; x < 6.0f; x += 0.05f)
		{
			
			if(y < 2.0f && y >= -2.0f && x < 2.0f && x > -2.0f)
			{
				printf("*");
			}
			else
			{
				printf(" ");
			}
		}
		Sleep(150);
		printf("\n");
	}
	return 0;
}

#include <stdio.h>
#include <Windows.h>

int main()
{
	system("color 0a");
	float x = 0.0f, y = 0.0f, a = 0.0f, b = 0.0f;
	for (y = 3.5f; y > -3.5f; y -= 0.075f)
	{
		for (x = -6.0f; x < 6.0f; x += 0.025f)
		{
			
			if(y < 2.0f && y >= -2.0f && x < 2.0f && x > -2.0f)
			{
				printf("*");
			}
			else
			{
				printf(" ");
			}
		}
		Sleep(150);
		printf("\n");
	}
	return 0;
}

在我的测试下,如果x、y的增量足够小,然后再把控制台缩放到最小尺寸,这时x与y的增量的关系最好是y = 3 * x。实际上不同的缩放程度会导致图形的不同程度的变形。

5、图形组合

#include <stdio.h>
#include <Windows.h>

int main()
{
	system("color 04");
	float x = 0.0f, y = 0.0f, a = 0.0f, b = 0.0f;
	for (y = 3.5f; y > -3.5f; y -= 0.075f)
	{
		for (x = -6.5f; x < 6.5f; x += 0.025f)
		{
			if (x * x / 32 + y * y / 8 < 1)
			{
				if (x * x + y * y < 8)
				{
					if (x * x / 8 + y * y / 2 < 1)
					{
						if (x * x + y * y < 2)
						{
							printf(" ");
						}
						else
						{
							printf("*");
						}
					}
					else
					{
						printf(" ");
					}
				}
				else
				{
					printf("*");
				}
			}
			else
			{
				printf(" ");
			}
		}
		Sleep(150);
		printf("\n");
	}
	return 0;
}

可以更改每个区域的字符使图像更绚烂

#include <stdio.h>
#include <Windows.h>

int main()
{
	system("color 0a");
	float x = 0.0f, y = 0.0f, a = 0.0f, b = 0.0f;
	for (y = 3.5f; y > -3.5f; y -= 0.075f)
	{
		for (x = -6.5f; x < 6.5f; x += 0.025f)
		{
			if(x * x / 32 + y * y / 8 < 1)
			{
				if(x * x + y * y < 8)
				{
					if(x * x / 8 + y * y / 2 < 1)
					{
						if(x * x + y * y < 2)
						{
							if(x * x / 2 + y * y / 0.5 < 1)
							{
								printf(" ");
							}
							else
							{
								if(y > 0)
								{
									printf("2");
								}
								else
								{
									printf("@");
								}
							}
						}
						else
						{
							printf(" ");
						}
					}
					else
					{
						printf("7");
					}
				}
				else
				{
					printf("#");
				}
			}
			else
			{
				printf(" ");
			}
		}
		Sleep(150);
		printf("\n");
	}
	return 0;
}

6、结语

当然,你们的想象力不应至于此,还有许多的图形等待你的探索,更多图形等待组合,也可以更改每个区域的字符使图像更绚烂。

  • 65
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
``` <!DOCTYPE html> <html> <head> <title></title> </head> <style> * { padding: 0; margin: 0; } html, body { height: 100%; padding: 0; margin: 0; background: #000; } canvas { position: absolute; width: 100%; height: 100%; } .aa { position: fixed; left: 50%; bottom: 10px; color: #ccc; } </style> <body> <canvas id="pinkboard"></canvas> <script> /* * Settings */ var settings = { particles: { length: 500, // maximum amount of particles duration: 2, // particle duration in sec velocity: 100, // particle velocity in pixels/sec effect: -0.75, // play with this for a nice effect size: 30 // particle size in pixels } }; /* * RequestAnimationFrame polyfill by Erik M?ller */ (function () { var b = 0; var c = ["ms", "moz", "webkit", "o"]; for (var a = 0; a < c.length && !window.requestAnimationFrame; ++a) { window.requestAnimationFrame = window[c[a] + "RequestAnimationFrame"]; window.cancelAnimationFrame = window[c[a] + "CancelAnimationFrame"] || window[c[a] + "CancelRequestAnimationFrame"]; } if (!window.requestAnimationFrame) { window.requestAnimationFrame = function (h, e) { var d = new Date().getTime(); var f = Math.max(0, 16 - (d - b)); var g = window.setTimeout(function () { h(d + f); }, f); b = d + f; return g; }; } if (!window.cancelAnimationFrame) { window.cancelAnimationFrame = function (d) { clearTimeout(d); }; } })(); /* * Point class */ var Point = (function () { function Point(x, y) { this.x = typeof x !== "undefined" ? x : 0; this.y = typeof y !== "undefined" ? y : 0; } Point.prototype.clone = function () { return new Point(this.x, this.y); }; Point.prototype.length = function (length) { if (typeof length == "undefined") return Math.sqrt(this.x * this.x + this.y * this.y); this.normalize(); this.x *= length; this.y *= length; return this; }; Point.prototype.normalize = function () { var length = this.length(); this.x /= length; this.y /= length; return this; }; return Point; })(); /* * Particle class */ var Particle = (function () { function Particle() { this.position = new Point(); this.velocity = new Point(); this.acceleration = new Point(); this.age = 0; } Particle.prototype.initialize = function (x, y, dx, dy) { this.position.x = x; this.position.y = y; this.velocity.x = dx; this.velocity.y = dy; this.acceleration.x = dx * settings.particles.effect; this.acceleration.y = dy * settings.particles.effect; this.age = 0; }; Particle.prototype.update = function (deltaTime) { this.position.x += this.velocity.x * deltaTime; this.position.y += this.velocity.y * deltaTime; this.velocity.x += this.acceleration.x * deltaTime; this.velocity.y += this.acceleration.y * deltaTime; this.age += deltaTime; }; Particle.prototype.draw = function (context, image) { function ease(t) { return --t * t * t + 1; } var size = image.width * ease(this.age / settings.particles.duration); context.globalAlpha = 1 - this.age / settings.particles.duration; context.drawImage( image, this.position.x - size / 2, this.position.y - size / 2, size, size ); }; return Particle; })(); /* * ParticlePool class */ var ParticlePool = (function () { var particles, firstActive = 0, firstFree = 0, duration = settings.particles.duration; function ParticlePool(length) { // create and populate particle pool particles = new Array(length); for (var i = 0; i < particles.length; i++) particles[i] = new Particle(); } ParticlePool.prototype.add = function (x, y, dx, dy) { particles[firstFree].initialize(x, y, dx, dy); // handle circular queue firstFree++; if (firstFree == particles.length) firstFree = 0; if (firstActive == firstFree) firstActive++; if (firstActive == particles.length) firstActive = 0; }; ParticlePool.prototype.update = function (deltaTime) { var i; // update active particles if (firstActive < firstFree) { for (i = firstActive; i < firstFree; i++) particles[i].update(deltaTime); } if (firstFree < firstActive) { for (i = firstActive; i < particles.length; i++) particles[i].update(deltaTime); for (i = 0; i < firstFree; i++) particles[i].update(deltaTime); } // remove inactive particles while ( particles[firstActive].age >= duration && firstActive != firstFree ) { firstActive++; if (firstActive == particles.length) firstActive = 0; } }; ParticlePool.prototype.draw = function (context, image) { // draw active particles if (firstActive < firstFree) { for (i = firstActive; i < firstFree; i++) particles[i].draw(context, image); } if (firstFree < firstActive) { for (i = firstActive; i < particles.length; i++) particles[i].draw(context, image); for (i = 0; i < firstFree; i++) particles[i].draw(context, image); } }; return ParticlePool; })(); /* * Putting it all together */ (function (canvas) { var context = canvas.getContext("2d"), particles = new ParticlePool(settings.particles.length), particleRate = settings.particles.length / settings.particles.duration, // particles/sec time; // get point on heart with -PI <= t <= PI function pointOnHeart(t) { return new Point( 160 * Math.pow(Math.sin(t), 3), 130 * Math.cos(t) - 50 * Math.cos(2 * t) - 20 * Math.cos(3 * t) - 10 * Math.cos(4 * t) + 25 ); } // creating the particle image using a dummy canvas var image = (function () { var canvas = document.createElement("canvas"), context = canvas.getContext("2d"); canvas.width = settings.particles.size; canvas.height = settings.particles.size; // helper function to create the path function to(t) { var point = pointOnHeart(t); point.x = settings.particles.size / 2 + (point.x * settings.particles.size) / 350; point.y = settings.particles.size / 2 - (point.y * settings.particles.size) / 350; return point; } // create the path context.beginPath(); var t = -Math.PI; var point = to(t); context.moveTo(point.x, point.y); while (t < Math.PI) { t += 0.01; // baby steps! point = to(t); context.lineTo(point.x, point.y); } context.closePath(); // create the fill context.fillStyle = "#ea80b0"; context.fill(); // create the image var image = new Image(); image.src = canvas.toDataURL(); return image; })(); // render that thing! function render() { // next animation frame requestAnimationFrame(render); // update time var newTime = new Date().getTime() / 1000, deltaTime = newTime - (time || newTime); time = newTime; // clear canvas context.clearRect(0, 0, canvas.width, canvas.height); // create new particles var amount = particleRate * deltaTime; for (var i = 0; i < amount; i++) { var pos = pointOnHeart(Math.PI - 2 * Math.PI * Math.random()); var dir = pos.clone().length(settings.particles.velocity); particles.add( canvas.width / 2 + pos.x, canvas.height / 2 - pos.y, dir.x, -dir.y ); } // update and draw particles particles.update(deltaTime); particles.draw(context, image); } // handle (re-)sizing of the canvas function onResize() { canvas.width = canvas.clientWidth; canvas.height = canvas.clientHeight; } window.onresize = onResize; // delay rendering bootstrap setTimeout(function () { onResize(); render(); }, 10); })(document.getElementById("pinkboard")); </script> </body> </html> ``` ![示例图片](https://devbit-static.oss-cn-beijing.aliyuncs.com/devbit-static/img/heart.png)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值