Как строить графики в си
Перейти к содержимому

Как строить графики в си

  • автор:

Программа на си для построения графика функции

В этой статье мы разберем программу на языке программирования си для построения графиков функций. В нашей программе будут отражаться система координат с делениями и подписями на них и будут строиться графики двух функций, который может сам задать пользователь.
В программе на си для построения графика функции вводятся следующие константы
X0 , Y0 — координаты центра координат
k – масштаб одного деления на осях (сколько пикселов в одном делении)
Опишем все функции и процедуры используемые в программе для построения графиков функций
Подробно о задании функций и процедур в си
int osx (float x) переводит реальную координату на оси ox в координату экрана
int osy (float y) переводит реальную координату на оси oy в координату экрана
float F1 ( float x ) и float F2 ( float x ) задают функции , графики которых мы будем строить
void Point ( float x, float y, int color ) рисует точку графика функции на экране
Перед построением графиков функций необходимо построить систему координат. Для построения системы координат используется процедура
void Axes()
В этой процедуре в цикле for рисуются линии меток делений на равном расстоянии друг от друга, который определяется масштабом одного деления k и выводятся значения делений с помощью двух операторов
sprintf ( s, "%d", i ); // записываем в строковую переменную число деления
outtextxy ( xe-10, Y0+4, s ); // вывод числа
Процедура grafik1() и grafik2() строят графики функций f1 и f2
В этих процедурах в цикле for для всех доступных значений x определяется координата y и точка графика строится с помощью процедуры point()

Пример работы программы построения графиков на си, функции пользователь может менять

графики функций на си

Программа на си для построения графиков функций
#include <stdio.h>
#include <graphics.h> //графический режим
#include <math.h> // математические функции

//————————————————
const int X0 = 100, Y0 = 400;// координаты центра координат
const float k = 15;// масштаб в точках одного деления на графике
//——————————————
// перевод y в координаты экрана
//——————————————
int osx (float x)
<
return X0+k*x;
>
//——————————————
//перевод y в координаты экрана
//——————————————
int osy (float y)
<
return Y0-k*y;
>
// первая функция
float F1 ( float x )
<
return sqrt(2*x);
>
// вторая функция
float F2 ( float x )
<
return x*x/2;
>
// построение осей
void Axes()
<
int i, xe,ye,y1;
char s[10];
line ( X0, 0, X0, 599 ); // ось ox
line ( 0, Y0, 799, Y0 ); // ось oy
// метки на оси ox
for ( i = 1; i <= (800-X0)/k; i ++ )
<
xe = osx ( i );
line ( xe, Y0-2, xe, Y0+2 ); // рисуем деление разметки
sprintf ( s, "%d", i ); // записываем в строковую переменную число деления
outtextxy ( xe-10, Y0+4, s ); // вывод числа
>
// метки на оси oy
for ( i = 1; i <= (Y0)/k; i ++ )
<
ye = osy( i+1 );
line ( X0-2, ye, X0+2, ye ); // рисуем деление
sprintf ( s, "%d",i ); // записываем в строковую переменную число деления
outtextxy ( X0+10, ye+4, s ); // вывод числа
>
>
// построение точки графика функции
void Point ( float x, float y, int color )
<
int xe, ye;
xe = osx(x);
ye = osy(y);
if ( xe >= 0 && xe < 800 && ye >= 0 && ye < 600 )
putpixel(xe, ye, color);
>
// построение графика первой функции
void grafik1()
<
float x, h, xmin, xmax;
h = 1 / k;
xmin = (-X0)/ k;
xmax=(800-X0)/k;
for ( x = xmin; x <= xmax; x += h )
<
Point(x, F1(x), WHITE);
>
>
// построение графика второй функции
void grafik2()
<
float x, h, xmin, xmax;
h = 1 / k;
xmin = (-X0)/ k;
xmax=(800-X0)/k;
for ( x = xmin; x <= xmax; x += h )
<
Point(x, F2(x), WHITE);
>
>
// главная программа
main ()
<
initwindow ( 800, 600 ); // создать окно для графики
Axes(); // построение и разметка осей координат
grafik1(); // строим график первой функции
grafik2(); // строим график второй функции
getch(); // ждать нажатия на клавишу
closegraph(); // закрыть окно для графики
>
Полезно почитать по теме построение графиков функций в программа си
Графика в си
Процедуры и функции в си

График функции в Си/Си++

Найти производные функции и на одном графике построить график данной функции, график первой и второй производной.
найти производные первого и второго порядка функции и на одном графике построить график данной.

Используя график функции построить график смещённой функции
используя график функции y=log2x построить график функции y=log2(x+2) Полностью решение нужно)))

Построить график функции y=x^2. График строится из отрезков и алгоритма Брезенхема
Построить график функции y=x^2. График строится с помощью отрезков. Для построения отрезков.

Составить график функции. Дана функция нужно построить график по полученным точкам
Помогите составить график функции. Дана функция нужно построить график по полученным точкам.

Как строить графики в си

//axes4(int x0,int y0,int xmin,int ymin,int xmax,int ymax,int bc,int gc,int fc,int ax);//constructor
//axes(int,int,int,int,int,int,int,int,int,int,int,int);

axes()
<
x0=y0=20;
xmin=-120;xmax=120;
ymin=-100;ymax=100;
bc=12;
gc=10;
fc=7;
zoom=1;
grdstp=1;
fstp=zoom/10.0;
gstp=1/fstp*grdstp;
ax=1;
a=1;
b=16;
c=8;
> //end of constructor */
void draw_grid();
void draw_function();
void clear();
>; //end of class

void graphit (char *path)
<
int gd, gm , err ;
gd = 9 ;
gm = 2 ;

initgraph (&gd, &gm, path);

err = graphresult();
/* an error occurred */
if (err != grOk)
<
printf("Graphics error: %s\n", grapherrormsg(err));
printf("Press any key to halt:");
getch();
exit(1);
>
>
void axes::init()
<
xcent=x0-xmin;
ycent=y0+ymax;
xend=xcent+xmax;
yend=ycent-ymin;
fstp=zoom/1.0;
gstp=18/fstp*3.141592*grdstp;

>
void axes::clear()
<
init();
setfillstyle(1,0);
bar(x0,y0,xend,yend);
>
void axes::draw_grid()
<
init();
if(xend>639) //.
xend=639; //.
if(yend>479) //.
yend=479; //.
setcolor(bc);
rectangle(x0,y0,xend,yend);
setcolor(fc);
if(ycent>y0&&ycent<yend)
line(x0,ycent,xend,ycent);
else
<
setcolor(fc-2);
if(ycent<=y0)
line(x0,y0,xend,y0);
else
line(x0,yend,xend,yend);
>
setcolor(fc);
if(xcent>x0&&xcent<xend)
line(xcent,y0,xcent,yend);
else
<
setcolor(fc-2);
if(xcent<=x0)
line(x0,y0,x0,yend);
else
line(xend,y0,xend,yend);
>
if(gstp<2)
gstp=0;
if(gstp&&ax)
<
for(x=-xmin%gstp+x0;x<xend;x+=gstp)
for(y=ymax%gstp+y0;y<yend;y+=gstp)
if(x>x0&&y>y0)
putpixel(x,y,gc);
>
>

void axes::draw_function()
<
int sign;
init();
for(x=xmin,xt=xmin*fstp;x<=xmax;x++,xt+=fstp)
<
y=sin((3.141592/180)*xt)*180/3.141592;//a*pow(xt,2)+b*xt+c;
yt=sin((3.141592/180)*(xt+fstp))*180/3.141592;//a*pow((xt+fstp),2)+b*(xt+fstp)+c;
sign=y<yt?1:-1;
while(y*sign<yt*sign)
<
if(y/fstp>ymin&&y/fstp<ymax)
<
putpixel(x+xcent,ycent-y/fstp,4);
//delay(1);
>
y+=sign*fstp;
>
>
>

Добавлено
вот вариант на си с тебя пиво

void graphit (char *path)
<
int gd, gm , err ;
gd = 9 ;
gm = 2 ;

initgraph (&gd, &gm, path);

err = graphresult();
/* an error occurred */
if (err != grOk)
<
printf("Graphics error: %s\n", grapherrormsg(err));
printf("Press any key to halt:");
getch();
exit(1);
>
>
void init()
<
xcent=x0-xmin;
ycent=y0+ymax;
xend=xcent+xmax;
yend=ycent-ymin;
fstp=zoom/1.0;
gstp=18/fstp*3.141592*grdstp;

>
void clear()
<
init();
setfillstyle(1,0);
bar(x0,y0,xend,yend);
>
void draw_grid()
<
init();
if(xend>639) //.
xend=639; //.
if(yend>479) //.
yend=479; //.
setcolor(bc);
rectangle(x0,y0,xend,yend);
setcolor(fc);
if(ycent>y0&&ycent<yend)
line(x0,ycent,xend,ycent);
else
<
setcolor(fc-2);
if(ycent<=y0)
line(x0,y0,xend,y0);
else
line(x0,yend,xend,yend);
>
setcolor(fc);
if(xcent>x0&&xcent<xend)
line(xcent,y0,xcent,yend);
else
<
setcolor(fc-2);
if(xcent<=x0)
line(x0,y0,x0,yend);
else
line(xend,y0,xend,yend);
>
if(gstp<2)
gstp=0;
if(gstp&&ax)
<
for(x=-xmin%gstp+x0;x<xend;x+=gstp)
for(y=ymax%gstp+y0;y<yend;y+=gstp)
if(x>x0&&y>y0)
putpixel(x,y,gc);
>
>

void draw_function()
<
int sign;
init();
for(x=xmin,xt=xmin*fstp;x<=xmax;x++,xt+=fstp)
<
y=sin((3.141592/180)*xt)*180/3.141592;//a*pow(xt,2)+b*xt+c;
yt=sin((3.141592/180)*(xt+fstp))*180/3.141592;//a*pow((xt+fstp),2)+b*(xt+fstp)+c;
sign=y<yt?1:-1;
while(y*sign<yt*sign)
<
if(y/fstp>ymin&&y/fstp<ymax)
<
putpixel(x+xcent,ycent-y/fstp,4);
//delay(1);
>
y+=sign*fstp;
>
>
>

void main()
<
char ch=' ';
int step=1;
// axes m[2];//(10,50,-100,-60,120,130,10,14,4,3,1);
graphit (bgipath) ;
x0=300;
y0=50;

xmin=-100;//left[-100];
xmax=100;//right[i];
ymin=-100;//down[i];
ymax=100;//up[i];
zoom=10;//zom[i];
draw_grid();
draw_function();

while((ch=getch())!='q')
<
switch(ch)
<
case 'e':ymax-=step;ymin-=step;break;
case 'x':ymax+=step;ymin+=step;break;
case 'd':xmin-=step;xmax-=step;break;
case 's':xmin+=step;xmax+=step;break;
case '6':zoom+=.1;break;
case '5':if(zoom>0.1)zoom-=.1;break;
case '7':if(step) step—;break;
case '8':step++;break;
case 'h':ymax=100;ymin=-100;xmin=-100;xmax=100;break;
case 'o':if(grdstp>1)grdstp—;break;
case 'p':grdstp++;
>

Код:

for(x=-xmin%gstp+x0;x<xend;x+=gstp) <
line(x,ycent-5,x,ycent+5);
>

вертикальные уж сам нарисуешь . с цифирьками не сложнее, но там нужно высчитывать когда их нужно перестать отображать, по тому как в определенный момент они будут налазить на друг друга
ln? да там все по аналогии, то что нужно учитывать что нет ln отрицательного числа

Код:

if(xt+1<=0) <
continue;
>

а то оно начинает рисовать с момента когда х=0, а не с х=-1

for(x=xmin,xt=xmin*fstp; x<=xmax; x++,xt+=fstp) <
if(xt-1<=0)
continue;

Код:

if(ycent>y0&&ycent<yend)
line(x0,ycent,xend,ycent); //если горизонтальная ось "находится" в окне
else
<
setcolor(fc-2);
if(ycent<=y0)
line(x0,y0,xend,y0); //если "выше" окна верхняя грань "окна" помечается другим цветом
else
line(x0,yend,xend,yend);// если "ниже" окна помечается нижняя грань
>
setcolor(fc);
if(xcent>x0&&xcent<xend)
line(xcent,y0,xcent,yend); //аналогично вертикальная ось
else
<
setcolor(fc-2);
if(xcent<=x0)
line(x0,y0,x0,yend);
else
line(xend,y0,xend,yend);
>

for(x=xmin+jmp,xt=xmin*fstp; x<=xmax-jmp; x++,xt+=fstp) <
y = sin((3.141592/180)*xt)*180/3.141592;
yt = sin((3.141592/180)*(xt+fstp))*180/3.141592;
sign = y < yt ? 1 : -1;

while(y*sign<yt*sign) <
if(y/fstp>ymin && y/fstp<ymax) <
putpixel(x+xcent,ycent-y/fstp,4);
//delay(1);
>

Линии лучше рисовать от центра, иначе отрезки с учетом осей будут различны:в
как я сделал:

Graphics in C Language

Graphics in C Language

In a C program, first step is to initialize the graphics drivers on the computer. This is done using the
initgraph ( )
method provided in
graphics . h
library. In the next few pages we will discuss graphics.h library in more details. Important functions in
graphic . h
library will be discussed in details and samples programs will be provided to show the power of C programming language especially for graphic programming developing graphical user interfaces.

We will restrict our discussion on Graphics in C to 16 bit C programming, MS DOS environment and 640×480 VGA monitor. Complete reference of graphics.h library and explanation of each method in that library can be found in the following articles.

Graphics mode Initialization – initgraph() function

First of all we call the
initgraph ( )
function that will initialize the graphics mode on the computer. The method
initigraph ( )
has the following prototype.
void initgraph ( int far * graphdriver , int far * graphmode , char far * pathtodriver ) ;
The method
initgraph ( )
initializes the graphics system by loading the graphics driver from disk (or validating a registered driver) then putting the system into graphics mode. The method
initgraph ( )
also resets all graphics settings (color, palette, current position, viewport, etc.) to their defaults. The initialization result is set to 0 which can be retrieved by calling
graphresult ( )
.

The
initgraph ( )
method has the following parameters.

*graphdriver

This is an integer value that specifies the graphics driver to be used. You can give
graphdriver
a value using a constant of the graphics_drivers enumeration type which is listed in
graphics . h
. Normally we use value as “0” (requests auto-detect). Other values are 1 to 10 and description of each enumeration type is listed here.

*graphmode

This is an integer value that specifies the initial graphics mode (unless
* graphdriver = DETECT
). If
* graphdriver = DETECT
, then
initgraph ( )
method sets *graphmode to the highest resolution available for the detected graphics driver. You can give *graphmode a value using a constant of the graphics_modes enumeration type and description of each enumeration type is listed here.

*pathtodriver

Specifies the directory path where
initgraph ( )
looks for graphics drivers (*.BGI) first.

  1. If they’re not there,
    initgraph ( )
    method looks in the current directory.
  2. If pathtodriver is null, the driver files must be in the current directory.

Both *graphdriver and *graphmode parameters must be set to valid graphics_drivers and graphics_mode values or you’ll get unpredictable results. (The exception is graphdriver = DETECT.)

After a call to
initgraph ( )
, *graphdriver is set to the current graphics driver, and *graphmode is set to the current graphics mode. You can tell initgraph to use a particular graphics driver and mode, or to auto detect the attached video adapter at run time and pick the corresponding driver. If you tell initgraph to auto detect, it calls detectgraph to select a graphics driver and mode.

The
initgraph ( )
method loads a graphics driver by allocating memory for the driver (through
_graphgetmem ( )
method call), then loading the appropriate .BGI file from disk. As an alternative to this dynamic loading scheme, you can link a graphics driver file (or several of them) directly into your executable program file.

Here is a simple program that initializes the graphics mode in C programming language and print the line in graphics mode.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *