爱心方程(专属理科生的浪漫?!)

目录

前言

C/C++

 源代码

扩展

Java

 Python

HTML

MATLAB


前言

这个在大一的时候就想找了,然后后面是找到了一个,但是忘记出处了。我决定把可以找到的所有爱心给整理一下,为了实现“理科生的浪漫”!!!

C/C++

首先就是可以调节他输出字体的颜色,默认当然是输出白色的,通过写一个函数来封装实现。如果参数越界了就默认输出白色了。这个我是当成固定写法的,要我记的话我也记不住。

#include<windows.h>
void color(int x){
	if(x>=0&&x<=15)
		SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),x);
	else
		SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),7);
}

 相关颜色参考如下:

color(0);printf("0     黑色\n");
color(1);printf("1     蓝色\n");
color(2);printf("2     绿色\n");
color(3);printf("3     湖蓝色\n");
color(4);printf("4     红色\n");
color(5);printf("5     紫色\n");
color(6);printf("6     黄色\n");
color(7);printf("7     白色\n");
color(8);printf("8     灰色\n");
color(9);printf("9     淡蓝色\n");
color(10);printf("10    淡绿色\n");
color(11);printf("11    淡浅绿色\n");
color(12);printf("12    淡红色\n");
color(13);printf("13    淡紫色\n");
color(14);printf("14    淡黄色\n");
color(15);printf("15    亮白色\n");

还要如何变帅一点,他输出的本质还是双重循环+换行输出,和输出三角形、菱形原理差不多。

现在主要就是这个爱心方程的公式,然后我是从网上找的一个,输出方面就是符合要求就输出目标字符(我这里是用星号*来表示),不符合方程的要求就输出空格就行了。

这个输出也有讲究,要直接全部打印出来吗,这显然不帅好吧,当然是逐个打印帅一点,这个的思路就是不让他全部一下子就打印出来了,要实现动态的效果,这就可以用到Sleep函数了。顾名思义就是睡眠的意思,以毫秒为单位,当你Sleep(1000)时就是一秒打印一个,这个速度按大家自己的想法。

这个爱心就大致出来了,然后还可以如何修改呢,我这里是根据我个人的喜好在里面输出一些语句,网抑云啊,什么的,怎么抑郁怎么来。

 源代码

#include<stdio.h>
#include<windows.h>
void color(int x){
	if(x>=0&&x<=15)
		SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),x);
	else
		SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),7);
}
void main(){
	printf("“愿我喜欢的人也在喜欢我!”");
	color(1);              //控制输出字体的颜色
	double x,y,a;
	for(y=1.5;y>-1.5;y-=0.1214){   //设置参数
		for(x=-1.5;x<1.5;x+=0.05){
			a=x*x+y*y-1;           //爱心方程
			if(a*a*a-x*x*y*y*y<=0){
				printf("*");//爱心构成的符号
				Sleep(1);
			}
			else
				printf(" ");
		}
		printf("\n");
	}
}

 这个也可以搞的花哨一点,弄一个五颜六色的,不同符号的输出。我这里颜色采用的组个递增的形式,当然也可以采用随机数啦,然后输出的非空白字符是采用随机数的形式,这里要排除不可以输出的字符,所有范围就缩小了,具体ASCII对应如下所示。

ASCII码一览表,ASCII码对照表 (biancheng.net)http://c.biancheng.net/c/ascii/

扩展

#include<stdio.h>
#include<windows.h>
#include<stdlib.h>
#include<time.h>

void color(int x){
	if(x>=0&&x<=15)
		SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),x);
	else
		SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),7);
}
void main(){
	srand((unsigned)time(NULL));//随机种子
	int countColor=0;  
	double x,y,a;
	for(y=1.5;y>-1.5;y-=0.1214){   //设置参数
		for(x=-1.5;x<1.5;x+=0.05){
			a=x*x+y*y-1;           //爱心方程
			if(a*a*a-x*x*y*y*y<=0){
				countColor++;		//记录当前输出的颜色
				countColor%=16;		//颜色范围取[0,15]
				color(countColor);	//控制输出字体的颜色
				int countChars=33+rand()%94;//排除无法输出的字符[33,126]
				putchar(countChars);	//爱心的构成符号
				Sleep(1);
			}
			else
				printf(" ");
		}
		printf("\n");
	}
}

 既然是知道他爱心方程的公式了,用其他语言来写就比较简单理解了。
(C++)万能头文件#include<bits/stdc++.h>_c语言万能头文件_Think@的博客-CSDN博客https://blog.csdn.net/qq_40728667/article/details/126825702

C/C++ 改变控制台输文字颜色:SetConsoleTextAttribute()_c++ setconsoletextattribute_杨 戬的博客-CSDN博客https://blog.csdn.net/weixin_45525272/article/details/121315941c++和c的差不多,直接修改就行了,这个貌似也没用到区别的地方。好像也没有什么区别吧。

这里的话没有cwindows还是要写成windows.h。网上找是没有找到。

[Error] cwindows: No such file or directory
//#include <bits/stdc++.h>
#include<iostream>
#include<cstdlib>
#include<ctime>
#include<windows.h>
using namespace std;

void color(int x){
	if(x>=0&&x<=15)
		SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),x);
	else
		SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),7);
}
int main(){
	srand((unsigned)time(NULL));//随机种子
	int countColor=0;  
	double x,y,a;
	for(y=1.5;y>-1.5;y-=0.1214){   //设置参数
		for(x=-1.5;x<1.5;x+=0.05){
			a=x*x+y*y-1;           //爱心方程
			if(a*a*a-x*x*y*y*y<=0){
				countColor++;		//记录当前输出的颜色
				countColor%=16;		//颜色范围取[0,15]
				color(countColor);	//控制输出字体的颜色
				int countChars=33+rand()%94;//排除无法输出的字符[33,126]
				putchar(countChars);	//爱心的构成符号
				Sleep(1);
			}
			else
				cout<<" ";
		}
		cout<<endl;
	}
	return 0;
}

Java

调了一下循环的界限,变长了一点,这个输出我的是卡顿的输出,没有那个连续的感觉,这个的话如果要那种感觉可以延长一下休眠的时间。输出是用的System.out.print,System.out.println输出会默认换行的。

java中的睡眠操作(sleep)_java 睡眠_豫章君的博客-CSDN博客https://blog.csdn.net/weixin_43929852/article/details/109264525

  • \033 是 ANSI 转义序列的起始字符,用于告诉终端后面跟着的是 ANSI 控制码。
  • [30m 是设置字体颜色的 ANSI 控制码,其中 30 代表字体颜色,后面的 m 表示设置结束。在 ANSI 控制码中,30 - 37 分别表示黑、红、绿、黄、蓝、品红、青、白这 8 种常用的字体颜色,而 m 则表示控制码的结束。
  • + "颜色" 即为需要输出的文本内容。
public class Color {
    public static void main(String[] args) {
        System.out.print("\033[30m"+"黑");
        System.out.print("\033[31m"+"红");
        System.out.print("\033[32m"+"绿");
        System.out.print("\033[33m"+"黄");
        System.out.print("\033[34m"+"蓝");
        System.out.print("\033[35m"+"品红");
        System.out.print("\033[36m"+"青");
        System.out.print("\033[37m"+"白");
    }
}

 

 这个颜色我感觉还是怪怪的,我这里选择的是青色。

public class EquationOfLove {
    public static void main(String[] args) throws InterruptedException {
        double x, y, a;
        for (y = 1.5; y > -1.5; y -= 0.1314) {
            for (x = -1.5; x < 1.5; x += 0.05) {
                a = x * x + y * y - 1;           //爱心方程
                if (a * a * a - x * x * y * y * y <= 0) {
                    System.out.print("\033[36m"+"*");//输出字符
                    Thread.sleep(50);//睡眠
                } else {
                    System.out.print(" ");//输出空格
                }
            }
            //换行
            System.out.println();
        }
    }
}

 Python

本来想用for循环加range的,但是里面的参数只能为整数。然后就是他的print是自带换行效果的。

Python for循环_老程序员的最大爱好的博客-CSDN博客https://blog.csdn.net/weixin_49892805/article/details/128189241python的print输出如何不换行_python print 不换行__房似锦_的博客-CSDN博客https://blog.csdn.net/xiatutut/article/details/125934871

TypeError: 'float' object cannot be interpreted as an integer

本来也想用C和Java的方法来写,发现怎么都输出不了,放弃了-_-,就只能用之前的turtle来写了,网上找了一个,然后自己修改了一下。自己写当然要挑一个粉色的啦!!!


from turtle import *
#笔尖的宽度
pensize(3)
#画笔颜色
color('pink')
#将海龟笔尖提起
penup()
#开始坐标
goto(0,-100)
#将海龟笔尖落下
pendown()
#逆时针150度,默认向右水平
setheading(150)
#爱心填充颜色
fillcolor('pink')
#开始填充
begin_fill()
#向前移动
fd(50)
#左半爱心
circle(50*-3.745,45)
circle(50*-1.431,165)
#向左旋转120
left(120)
#右半爱心
circle(50*-1.431,165)
circle(50*-3.745,45)
fd(50)
#结束填充
end_fill()
# 隐藏turtle图形(箭头)
hideturtle()
#暂停程序,停止画笔绘制,但绘图窗体不关闭,直到用户关闭pythonTurtle图形化窗口为止
done()

 这边就有更加炫酷的了。

爱心代码李峋同款爱心 python html_py画爱心代码tkinter_CL_Young的博客-CSDN博客https://blog.csdn.net/CL_Young/article/details/127808312?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522168338430116800188524024%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=168338430116800188524024&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~top_positive~default-2-127808312-null-null.142%5Ev86%5Einsert_down38v5,239%5Ev2%5Einsert_chatgpt&utm_term=%E7%88%B1%E5%BF%83%E4%BB%A3%E7%A0%81%E5%A4%A7%E5%85%A8html&spm=1018.2226.3001.4187

HTML

这个还是前面那个博主的爱心,我直接抄袭下来了。

 对代码修改:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>爱心方程</title>
 
    <style>
      html,
      body {
        height: 100%;
        padding: 0;
        margin: 0;
        background: #000;
      }
      canvas {
        position: absolute;
        width: 100%;
        height: 100%;
        animation: anim 1.5s ease-in-out infinite;
        -webkit-animation: anim 1.5s ease-in-out infinite;
        -o-animation: anim 1.5s ease-in-out infinite;
        -moz-animation: anim 1.5s ease-in-out infinite;
      }
      #name {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        margin-top: -20px;
        font-size: 46px;
        color: #ea80b0;
      }
      @keyframes anim {
        0% {
          transform: scale(0.8);
        }
        25% {
          transform: scale(0.7);
        }
        50% {
          transform: scale(1);
        }
        75% {
          transform: scale(0.7);
        }
        100% {
          transform: scale(0.8);
        }
      }
      @-webkit-keyframes anim {
        0% {
          -webkit-transform: scale(0.8);
        }
        25% {
          -webkit-transform: scale(0.7);
        }
        50% {
          -webkit-transform: scale(1);
        }
        75% {
          -webkit-transform: scale(0.7);
        }
        100% {
          -webkit-transform: scale(0.8);
        }
      }
      @-o-keyframes anim {
        0% {
          -o-transform: scale(0.8);
        }
        25% {
          -o-transform: scale(0.7);
        }
        50% {
          -o-transform: scale(1);
        }
        75% {
          -o-transform: scale(0.7);
        }
        100% {
          -o-transform: scale(0.8);
        }
      }
      @-moz-keyframes anim {
        0% {
          -moz-transform: scale(0.8);
        }
        25% {
          -moz-transform: scale(0.7);
        }
        50% {
          -moz-transform: scale(1);
        }
        75% {
          -moz-transform: scale(0.7);
        }
        100% {
          -moz-transform: scale(0.8);
        }
      }
    </style>
  </head>
  <body>
    <canvas id="pinkboard"></canvas>
    <!-- 在下面加名字 -->
     <div id="name" style="color: pink;">平安喜乐</div> 
 
    <script>
      var settings = {
        particles: {
          length: 500, 
          duration: 2, 
          velocity: 100, 
          effect: -0.75,
          size: 30, 
        },
      };
      (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);
          };
        }
      })();
      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;
      })();
      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;
      })();
      var ParticlePool = (function () {
        var particles,
          firstActive = 0,
          firstFree = 0,
          duration = settings.particles.duration;
 
        function ParticlePool(length) {
          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);
          firstFree++;
          if (firstFree == particles.length) firstFree = 0;
          if (firstActive == firstFree) firstActive++;
          if (firstActive == particles.length) firstActive = 0;
        };
        ParticlePool.prototype.update = function (deltaTime) {
          var i;
          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);
          }
          while (
            particles[firstActive].age >= duration &&
            firstActive != firstFree
          ) {
            firstActive++;
            if (firstActive == particles.length) firstActive = 0;
          }
        };
        ParticlePool.prototype.draw = function (context, image) {
          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;
      })();
      (function (canvas) {
        var context = canvas.getContext("2d"),
          particles = new ParticlePool(settings.particles.length),
          particleRate =
            settings.particles.length / settings.particles.duration, 
          time;
        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
          );
        }
        var image = (function () {
          var canvas = document.createElement("canvas"),
            context = canvas.getContext("2d");
          canvas.width = settings.particles.size;
          canvas.height = settings.particles.size;
          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;
          }
          context.beginPath();
          var t = -Math.PI;
          var point = to(t);
          context.moveTo(point.x, point.y);
          while (t < Math.PI) {
            t += 0.01;
            point = to(t);
            context.lineTo(point.x, point.y);
          }
          context.closePath();
          context.fillStyle = "#ea80b0";
          context.fill();
          var image = new Image();
          image.src = canvas.toDataURL();
          return image;
        })();
        function render() {
          requestAnimationFrame(render);
          var newTime = new Date().getTime() / 1000,
            deltaTime = newTime - (time || newTime);
          time = newTime;
          context.clearRect(0, 0, canvas.width, canvas.height);
          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
            );
          }
          particles.update(deltaTime);
          particles.draw(context, image);
        }
        function onResize() {
          canvas.width = canvas.clientWidth;
          canvas.height = canvas.clientHeight;
        }
        window.onresize = onResize;
        setTimeout(function () {
          onResize();
          render();
        }, 10);
      })(document.getElementById("pinkboard"));
 
    </script>
  </body>
</html>

MATLAB

这个用MATLAB画的爱心还是蛮震撼的我还是比较喜欢曲线那个。

Matlab中爱心的四种画法(附代码)_matlab爱心代码_CarenStrid的博客-CSDN博客https://blog.csdn.net/CarenStrid/article/details/127171616matlab中fill函数的使用方法_matlab fill_平平无奇的小女子~的博客-CSDN博客https://blog.csdn.net/onlyfanlala/article/details/121707456一些心型曲线及其方程_心形曲线_stereohomology的博客-CSDN博客https://blog.csdn.net/stereohomology/article/details/51581391笛卡尔心形函数表达式_数学的有趣图形-心形线_江东的铁壁的博客-CSDN博客https://blog.csdn.net/weixin_35117981/article/details/112368380

心脏曲线 -- 来自 Wolfram MathWorldhttps://mathworld.wolfram.com/HeartCurve.html

 这里的plot的函数一般是两个参数,后面的参数是用来设置他的颜色以及线型的。我这里用的是蓝色的线条。

MATLAB:plot函数详解_matlab plot_孙 悟 空的博客-CSDN博客https://blog.csdn.net/weixin_46098577/article/details/119520546

  • ‘b’:蓝色
  • ‘g’:绿色
  • ‘r’:红色
  • ‘c’:青色
  • ‘m’:品红色
  • ‘y’:黄色
  • ‘k’:黑色
  • ‘w’:白色
%x的取值[-2,2],步长1/500
x = -2:1/500:2;
%用x表示y
y = abs(x .^ (2/3)) + (0.99 * (3.3 - x .^ 2) .^ (1/2)) .* sin(9.9 * pi * x);
%带入方程绘制图像,颜色是'blue'
plot(x, y,'b');
%图像的标题
title('Romantic till death do us part');

%生成100个线性间断向量
r=linspace(-pi,pi);
%x=2(sinr-(sin2r)/2)
x=2*(sin(r)-sin(2*r)./2);
%y=2(cosr-cosr^2)
y=2*(cos(r)-cos(r).^2);
%曲线的颜色
plot(x,y,'r');
title('You’re the missing piece to my puzzle')

 

 也就改成填充颜色,表示线条颜色,就要用到fill函数了。fill(x,y,'r');

%生成100个线性间断向量
r=linspace(-pi,pi);
%x=2(sinr-(sin2r)/2)
x=2*(sin(r)-sin(2*r)./2);
%y=2(cosr-cosr^2)
y=2*(cos(r)-cos(r).^2);
%填充的颜色
fill(x,y,'r');
title('You’re the missing piece to my puzzle')

那整理就到此为止了,喜欢的小伙伴可以点赞多多支持一下。

猜你喜欢

转载自blog.csdn.net/weixin_64066303/article/details/131351893
今日推荐