x^2 + (y-(x^2)(1/3))^2 = 1 心形方程 5.20无聊之作

2017.05.20 一个无聊的周六,只能看别人秀恩爱.偶然间在网上看到一个有意思的方程 x^2 + (y-(x^2)(1/3))^2 = 1,据说这个方程可以绘制出一个爱心的形状.既然很无聊,就随便动手实现了.

附:opengl开发库 http://pan.baidu.com/s/1mip2pja

#include <stdio.h>
#include "glut.h"
#include "math.h"

// x^2 + (y-(x^2)(1/3))^2 = 1
// y = (+/-)sqrt(1-x^2) + (x^2)(1/3)
void love_fun(float x, float &y1, float &y2)
{
    if (x > 1.0)
    {
        return;
    }
    float a = pow(x, 2.0f);
    float b = sqrt(1 - a);
    float c1 = b;
    float c2 = -b;
    float d = pow(a, 0.333333f);
    y1 = c1 + d;
    y2 = c2 + d;
}

void coordinate()
{
    glColor3f(1.0, 1.0, 1.0);
    glBegin(GL_LINES);
    glVertex3f(-2.0, 0.0f, 0.0);
    glVertex3f(2.0, 0.0f, 0.0);
    glVertex3f(0.0, -2.0f, 0.0);
    glVertex3f(0.0, 2.0f, 0.0);
    glEnd();
}

void love()
{
    float step = 0.0005f;
    glColor3f(1.0, 0.0, 0.0);
    glBegin(GL_POLYGON);
    for (float x = -1.0; x <= 1.0; x += step)
    {
        float y1 = 0, y2 = 0;
        love_fun(x, y1, y2);
        // printf("(%f %f) (%f %f)
", x, y1, x, y2);
        glVertex3f(x, y1, 0.0);
        glVertex3f(x, y2, 0.0);
    }
    glEnd();
}

void display_love()
{
    glClear(GL_COLOR_BUFFER_BIT);
    love();
    coordinate();
    glutSwapBuffers();
}

void init(void)
{

    glClearColor(0.4, 0.4, 0.8, 0.0);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-2.0f, 2.0f, -2.0f, 2.0f, -1.0f, 1.0f);
}


int main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
    glutInitWindowPosition(500, 100);
    glutInitWindowSize(600, 500);
    glutCreateWindow("love : x^2 + (y-(x^2)(1/3))^2 = 1");
    init();
    glutDisplayFunc(display_love);
    glutMainLoop();
    return 0;
}
原文地址:https://www.cnblogs.com/tangxin-blog/p/6883056.html