[英]draw graph of the function in C graphics
我正在尝试绘制函数图。 如何正确地做到这一点,我在互联网上找不到任何资源。
代码:
#include <graphics.h>
#include <math.h>
#define G GREEN
int main()
{
int gd = DETECT, gm, angle = 0;
double x, y;
initgraph(&gd, &gm, NULL);
int cx = getmaxx()/2, cy = getmaxy()/2;
line(20, cy, getmaxx()-20, cy);
line(cx, 20, cx, getmaxy()-20);
outtextxy(cx, cy, "O");
//y=5*x-3*sinx^2(k*x) y=cos(k*x) y=4x^7-3x^3+5
setcolor(GREEN);
for (x = 0; x < getmaxx(); x+=0.01) {
/* Calculate y with given x */
y = 4 * pow(x, 7) - (3 * pow(x, 3) + 5);
y = cy - y;
/* Coloring pixel at x and y */
if (y < 0) {
break;
}
putpixel(x+cx, y, GREEN);
delay(50);
}
for (x = 0; x < getmaxx() && x+cx >= 0; x-=0.01) {
/* Calculate y with given x */
y = 4 * pow(x, 7) - 3 * pow(x, 3) + 5;
y = cy - y;
/* Coloring pixel at x and y */
if (y > getmaxy())
break;
putpixel(x+cx, y, GREEN);
delay(50);
}
getch();
closegraph();
return (0);
}
我需要它更显眼而不是那么瘦。 会有什么办法。 这里还有要实现的功能:(我从最后一个功能开始)
编辑:所以对于那些感兴趣的人,我做到了,代码在这里
为了让您的像素更加可见,请使用例如半径为 2 的圆盘(半径 1 可能就足够了)。
fillellipse(x+cx, y, 2, 2);
您可以在点之间画线以获得非常好的“图形”印象,
但要注意不要在定义间隙处错误地表示。
例如,从 (X=-0.1,Y=1/-0,1) 到 (X=0.1,Y=1/0,1) 画一条线是错误的。
line(x1, y1, x2, y2);
正如评论所指出的,调整两个轴的缩放比例可能会改善印象,但这可能仅适用于单个图形。 具有不同极值的几个人中的一个可能仍然看起来很瘦。
所以,因为它的古老图书馆里我的大学仍然使用它面临着棕榈感兴趣的人我搞清楚。
代码:
#include <graphics.h>
#include <math.h>
#define G GREEN
#define X_AXIS 2
#define Y_AXIS 7
void draw_last(float direction)
{
double x = 0, y, px, py, cx = getmaxx()/2, cy = getmaxy()/2;
while (x <= X_AXIS && x >= -X_AXIS) {
/* Calculate y with given x */
y = 4 * pow(x, 7) - 3 * pow(x, 3) + 5;
/* Calculate coordoninates to display */
px = x * cx / X_AXIS + cx;
/* -cy because of origin point in window(top left corner) */
py = y * -cy / Y_AXIS + cy;
/* in case boundaries are passed */
if (py < 0 || py > getmaxy())
break;
if (x == 0) // only for first loop
moveto(px, py);
/* Draw segment line */
lineto(px, py);
/* update CP */
moveto(px, py);
x += direction;
delay(20);
}
}
int main()
{
int gd = DETECT, gm;
initgraph(&gd, &gm, NULL);
/* Draw the axis */
int cx = getmaxx()/2, cy = getmaxy()/2;
line(20, cy, getmaxx()-20, cy);
line(cx, 20, cx, getmaxy()-20);
outtextxy(cx, cy, "O");
outtextxy(20, cy, "-2");
outtextxy(getmaxx()-20, cy, "2");
outtextxy(cx, 20, "7");
outtextxy(cx, getmaxy()-20, "-7");
setcolor(GREEN);
setlinestyle(SOLID_LINE, 0, 2);
/* from x=0 ++ */
draw_last(0.01);
/* from x=0 -- */
draw_last(-0.01);
getch();
closegraph();
return (0);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.