Поиск:

Закрытая темаСоздание новой темы Создание опроса
> Коллекция алгоритмов от Johna Smith, в качестве учебного материала 
:(
    Опции темы
podval
Дата 21.12.2004, 17:52 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Где я? Кто я?
****


Профиль
Группа: Экс. модератор
Сообщений: 3094
Регистрация: 25.3.2002
Где: СПб

Репутация: 18
Всего: 62



 Выложенные здесь алгоритмы преследуют исключительно учебные цели. 
Код неоптимизирован, местами морально устарел и показывает только принцип решения той или иной задачи. Однако он вполне рабочий и может быть использован с соответствующей дорботкой под Ваши собственные нужды.

Содержание

    * Перевод из... в...
    * Графические алгоритмы
    * Специальные функции
    * Динамические структуры данных
    * Сортировка массивов
    * Сортировка файлов
    * Методы поиска
    * Матрицы
    * Операции с комплексными величинами
    * Математическая статистика
    * Интегрирование функций
    * Календарь
    * Решение систем линейных уравнений
    * Решение нелинейных уравнений
    * Интерполяция
    * Операции с полиномами
    * Сжатие и шифрование
    * Решение дифференциальных уравнений
    * Вычисление CRC
    * Разное


 Перевод из... в...


Градусы, минуты, секунды - в градусы

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Translating angle from degrees, minutes, seconds to degrees
//  (c) Johna Smith, 1996
//
//  Method description:
//    Here we just use the following formula:
//      phi=(phi"/60+phi')/60+phiш
//
//////////////////////////////////////////////////////////////////////////////

#include <stdio.h>

struct angle
{
  float degrees;
  float minutes;
  float seconds;
};

void print_angle(angle a)
{
  printf("%fш%f'%f\"",a.degrees,a.minutes,a.seconds);
}

float dms_to_d(angle a)
{
  float f;

  f=(a.seconds/60+a.minutes)/60+a.degrees;

  return f;
}

void main(void)
{
  angle a={30,30,30};

  print_angle(a);
  printf("= %fш",dms_to_d(a));
}



Градусы - в градусы, минуты, секунды

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Translating angle from degrees to degrees, minutes, seconds
//  (c) Johna Smith, 1996
//
//  Method description:
//    degrees is the integer part of angle f
//    minutes is the integer part of the remainder multiplied by 60
//    seconds is the integer part of 60*(phi_in_minutes-phi')
//
//////////////////////////////////////////////////////////////////////////////

#include <stdio.h>

struct angle
{
  float degrees;
  float minutes;
  float seconds;
};

void print_angle(angle a)
{
  printf("%fш%f'%f\"",a.degrees,a.minutes,a.seconds);
}

angle d_to_dms(float f)
{
  angle a;

  a.degrees=(int)f;
  a.minutes=(int)((f-a.degrees)*60);
  a.seconds=(int)((f-a.degrees)*60-a.minutes);

  return a;
}

void main(void)
{
  printf("12.3456ш=");
  print_angle(d_to_dms(12.3456));
}




Комплексных величин - в экспоненциальную форму

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Complex values operations (converting from a+bi form to M*exp(i*phi))
//  (c) Johna Smith, 1996
//
//  Given: z - complex value
//  z=a+i*b
//  z=M*exp(i*phi)
//  M=(a^2+b^2)^(1/2)    phi=arccos(a/|M|)
//
//////////////////////////////////////////////////////////////////////////////

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

struct complex
{
  float re;
  float im;
};

struct exp_complex
{
  float M;
  float phi;
};

void show_complex(complex c) // this functions displays complex value
{
  printf("%f%+fi",c.re,c.im);
}

void show_exp_complex(exp_complex c) // this functions displays complex value
{
  printf("%f*exp(%f*i)",c.M,c.phi);
}

exp_complex Convert(complex a)
{
  exp_complex b;

  b.M=sqrt(a.re*a.re+a.im*a.im);
  b.phi=(a.im<0?-1:1)*acos(a.re/fabs(b.M));

  return b;
}

complex a={-1,1};

void main(void)
{
  show_complex(a);
  printf(" = ");
  show_exp_complex(Convert(a));
}

 

Это сообщение отредактировал(а) maxim1000 - 5.5.2008, 21:08
PM WWW ICQ   Вверх
podval
Дата 22.12.2004, 08:53 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Где я? Кто я?
****


Профиль
Группа: Экс. модератор
Сообщений: 3094
Регистрация: 25.3.2002
Где: СПб

Репутация: 18
Всего: 62



Градусы по Фаренгейту - в градусы по Цельсию

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Translatintg Farengheit degrees to Celsy degrees and in other direction
//  (c) Johna Smith, 1996
//
//  Method description:
//
//    oF = 5/9(n-32) oC     oC = (32+9n/5) oF
//////////////////////////////////////////////////////////////////////////////

#include <stdio.h>

float Cels2Fareng(float degree)
{
 return (5*(degree-32)/9);
}

float Fareng2Cels(float degree)
{
 return (32+9*degree/5);
}

void main(void)
{
 printf("100oC = %f oF\n",Cels2Fareng(100));
 printf("-50oF = %f oC\n",Fareng2Cels(-50));
}





Декартовы координаты - в полярные (2D)

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Translatintg Decart coordinates to polar coordinates in 2 dimensions
//  (c) Johna Smith, 1996
//
//  Method description:
//
//  r=(x^2+y^2)^(1/2)
//  phi=+/- arccos(x/r)
//////////////////////////////////////////////////////////////////////////////

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

struct decart
{
 float x;
 float y;
};

struct polar
{
 float r;
 float phi;
};

polar Decart2Polar(decart c)
{
 polar p;

 p.r=sqrt(c.x*c.x+c.y*c.y);
 p.phi=acos(c.x/p.r)*(c.y>=0?1:-1);

 return p;
}

decart d={1,1};
polar p;

void main(void)
{
 p=Decart2Polar(d);
 printf("(x,y)=(%f,%f) -> (r,phi)=(%f,%f)\n",d.x,d.y,p.r,p.phi);
}




Полярные - в декартовы

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Translatintg polar coordinates to Decart coordinates in 2 dimensions
//  (c) Johna Smith, 1996
//
//  Method description:
//
//  x=r*cos(phi)
//  y=r*sin(phi)
//
//////////////////////////////////////////////////////////////////////////////

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

#define Pi 3.1415926536

struct decart
{
 float x;
 float y;
};

struct polar
{
 float r;
 float phi;
};

decart Polar2Decart(polar p)
{
 decart d;

 d.x=p.r*cos(p.phi);
 d.y=p.r*sin(p.phi);

 return d;
}

polar p={1.4142135624,Pi/4};
decart d;

void main(void)
{
 d=Polar2Decart(p);
 printf("(r,phi)=(%f,%f) -> (x,y)=(%f,%f)\n",p.r,p.phi,d.x,d.y);
}



Декартовы координаты - в сферические (3D)

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Translatintg Decart coordinates to spherical coordinates in 3 dimensions
//  (c) Johna Smith, 1996
//
//  Method description:
//
//  r=(x^2+y^2+z^2)^(1/2)
//  phi=+/- arccos(x/(x*x+y*y)^(1/2))
//  theta=arccos(z/r)
//
//////////////////////////////////////////////////////////////////////////////

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

struct decart
{
 float x;
 float y;
 float z;
};

struct spherical
{
 float r;
 float phi;
 float theta;
};

spherical Decart2Spherical(decart c)
{
 spherical p;

 p.r=sqrt(c.x*c.x+c.y*c.y+c.z*c.z);
 p.phi=acos(c.x/sqrt(c.x*c.x+c.y*c.y))*(c.y>=0?1:-1);
 p.theta=acos(c.z/p.r);

 return p;
}

decart d={1,1,1};
spherical p;

void main(void)
{
 p=Decart2Spherical(d);
 printf("(x,y,z)=(%f,%f,%f) -> (r,phi,theta)=(%f,%f,%f)\n",
        d.x,d.y,d.z,p.r,p.phi,p.theta);
}




Сферические - в декартовы

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Translatintg spherical coordinates to Decart coordinates in 3 dimensions
//  (c) Johna Smith, 1996
//
//  Method description:
//
//  x=r*cos(phi)*sin(theta)
//  y=r*sin(phi)*sin(theta)
//  z=r*cos(theta)
//
//////////////////////////////////////////////////////////////////////////////

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

#define Pi 3.1415926536

struct decart
{
 float x;
 float y;
 float z;
};

struct spherical
{
 float r;
 float phi;
 float theta;
};

decart Spherical2Decart(spherical p)
{
 decart d;

 d.x=p.r*cos(p.phi)*sin(p.theta);
 d.y=p.r*sin(p.phi)*sin(p.theta);
 d.z=p.r*cos(p.theta);

 return d;
}

spherical p={1.732051,0.785398,0.955317};
decart d;

void main(void)
{
 d=Spherical2Decart(p);
 printf("(r,phi,theta)=(%f,%f,%f) -> (x,y,z)=(%f,%f,%f)\n",
        p.r,p.phi,p.theta,d.x,d.y,d.z);
}

PM WWW ICQ   Вверх
podval
Дата 22.12.2004, 09:16 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Где я? Кто я?
****


Профиль
Группа: Экс. модератор
Сообщений: 3094
Регистрация: 25.3.2002
Где: СПб

Репутация: 18
Всего: 62



Число из системы с основанием М - в систему с основанием N

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Translating number from M-system to N-system
//  (c) Johna Smith, 1996
//
//  Method description:
//    1) translate number to decimal
//    2) translate from decimal using sequence of divisions by nbase
//       remainders will be digits of the number in the new system
//
//////////////////////////////////////////////////////////////////////////////

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

enum digit {A=10,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z};

char mbase=16;    // from hex
char nbase=2;  // to binary

digit m[]={F,E,D,C,B,A};  // (FEDCBA)(16)
digit n[255];

void main(void)
{
 unsigned long int decimal=0,tmp=1;
 float tmpf;

 // printing given number
 for (int i=0;i<sizeof(m)/sizeof(digit);i++)
   if (m[i]<10)
      printf("%d",m[i]);
   else printf("%c",m[i]+55);
 
 // translate number to decimal
 for(i=sizeof(m)/sizeof(digit)-1;i>=0;i--)
 {
    decimal+=tmp*m[i];
    tmp*=mbase;
 }
 printf("(%d) = %ld(10) = ",mbase,decimal);
 
 // translating from decimal
 tmpf=(float)log(decimal/(nbase-1))/log(nbase);
 // rounding to nearest integer
 tmp=(int)tmpf;
 
 if (tmpf-tmp>0.5) tmp++;
 
 for (i=tmp;i>=0;i--)
 {
   n[i]=decimal%nbase;
   decimal/=nbase;
 }
 
 // printing converted number
 for (i=0;i<=tmp;i++)
   if (n[i]<10)
     printf("%d",n[i]);
   else printf("%c",n[i]+55);
 printf("(%d)\n",nbase);
}



Приведение периодической дробной части к нормальному виду

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Transforming periodical decimal fraction to normal one.
//  (c) Johna Smith, 1996
//
//  Method description:
//    This method uses the fact that periodical fraction can be
//   calculated as a sum of infinite geometr. progression = 1/(1-q).
//    For example: 235.353535353...
//    The period is 35, the base (aperiodical part of the fraction) is 200,
//   number of digits in the period is 2. These parameters are required by
//   function Convert.
//    q=10^(-2)  x0=35   SUM=x0+q*x0+q^2*x0+q^3*x0+...
//
//////////////////////////////////////////////////////////////////////////////

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

struct fraction
{
 long int a;
 long int b;
 long int c;
} f;    // f=a+b/c

fraction Convert(double base, double period, int digits)
{
 fraction f;
 double tmp;

 f.a=0;
 f.b=pow10(digits);
 f.c=f.b-1;

 // calculating 1/(1-q)
 tmp=(double)f.b*period;
 while (floor(tmp)!=tmp)
 {
    tmp*=10;
    f.b*=10;
    f.c*=10;
 }
 f.b*=period;

 // adding base to the fraction
 base*=f.c;
 while (floor(base)!=base)
 {
    base*=10;
    f.b*=10;
    f.c*=10;
 }

 f.b+=base;
 // if this fraction isn't right: b>c we should convert it
 // into the right fraction a+ b1/c, where b1<c1 & a*c+b1=b
 if (f.b/f.c>1)
 {
    f.a+=(int)(f.b/f.c);
    f.b-=((int)(f.b/f.c))*f.c;
 }

 return f;
}

void main(void)
{
 f=Convert(200,35,2);
 printf("235,(35) = %ld %ld/%ld\n",f.a,f.b,f.c);
 f=Convert(0.0783,441e-7,3);
 printf("0.0783(441) = %ld %ld/%ld",f.a,f.b,f.c);
}


PM WWW ICQ   Вверх
podval
Дата 22.12.2004, 09:31 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Где я? Кто я?
****


Профиль
Группа: Экс. модератор
Сообщений: 3094
Регистрация: 25.3.2002
Где: СПб

Репутация: 18
Всего: 62



Графические алгоритмы

Рисование 3D объекта

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Drawing 3D object
//  (c) Johna Smith, 1996
//
//  Method description:
//    Function draw3Dobject recieves the following parameters:
//     object - reference to array of points of the drawn object
//     N - number of points in this array
//     rho     \
//     phi     |- spherical coordinates of point of view
//     theta   /
//     dist_to_screen - distance from viewpoint to screen
//     xshift, yshift - picture will be shifted by this values
//
//////////////////////////////////////////////////////////////////////////////

#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <math.h>
#include <dos.h>

#define Pi 3.1415926536

enum Action{move,draw};

struct Point3D
{
 int x;
 int y;
 int z;
 Action action;
};

// this function initializes graphics mode
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void init_gr(void)
{
       /* request autodetection */
       int gdriver = DETECT, gmode, errorcode;

       /* initialize graphics mode */
       initgraph(&gdriver, &gmode, "");

       /* read result of initialization */
       errorcode = graphresult();

       if (errorcode != grOk)    /* an error occurred */
     {
               printf("Graphics error: %s\n", grapherrormsg(errorcode));
               printf("Press any key to halt:");
                                        getch();
               exit(1);               /* return with error code */
       }
}

// this function shuts graphics mode down
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void end_gr(void)
{
 closegraph();
}

// this function moves CP to (x,y) position
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void MoveTo(int x, int y)
{
 moveto(x,y);
}

// this function draws a line to (x,y) position
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void LineTo(int x, int y)
{
 lineto(x,y);
}

void draw3Dobject(Point3D *object, int N, float rho, float theta,
                 float phi, float dist_to_screen, int xshift, int yshift)
{
 int x,y;
 float xe,ye,ze,costh,sinph,cosph,sinth,v11,v12,v13,v21,v22,v32,v33,v23,v43;

 // calculating coefficients
 costh=cos(theta);
 sinth=sin(theta);
 cosph=cos(phi);
 sinph=sin(phi);
 v11=-sinth; v12=-cosph*costh; v13=-sinph*costh;
 v21=costh;  v22=-cosph*sinth; v23=-sinph*sinth;
                                 v32=sinph;        v33=-cosph;
                               v43=rho;
 for (int i=0;i<N;i++)
 {
     // calculating eye coordinates
     xe=v11*(object+i)->x+v21*(object+i)->y;
     ye=v12*(object+i)->x+v22*(object+i)->y+v32*(object+i)->z;
     ze=v13*(object+i)->x+v23*(object+i)->y+v33*(object+i)->z+v43;
     // calculating screen coordinates
     x=dist_to_screen*xe/ze+xshift;
     y=dist_to_screen*ye/ze+yshift;
     // drawing
     if((object+i)->action==move)
         MoveTo(x,y);
     else
         LineTo(x,y);
 }
}

int main(void)
{
 Point3D thetr[]={{100,100,100,move},
                             {100,200,100,draw},
                             {200,100,100,draw},
                             {100,100,100,draw},
                             {100,100,200,draw},
                             {200,100,100,draw},
                             {100,100,200,move},
                             {100,200,100,draw}};
 int N=sizeof(thetr)/sizeof(Point3D);
 float rho=700,theta=Pi/4,phi=Pi/4,dist_to_screen=300;
 int xshift=300, yshift=150;

 // initializing graphics mode
 init_gr();

 /* examples */
 while (!kbhit())
 {
     theta+=0.05;
     // rotating viewpoint
     if (phi>2*Pi) phi-=2*Pi;
     setcolor(11);
     draw3Dobject(thetr,N,rho,theta,phi,dist_to_screen,xshift,yshift);
     setcolor(0);
     delay(15);
     draw3Dobject(thetr,N,rho,theta,phi,dist_to_screen,xshift,yshift);
 }

 /* clean up */
 getch();
 end_gr();

 return 0;
}



Вращение 3D объекта

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Rotating 3D object
//  (c) Johna Smith, 1996
//
//  Method description:
//   Given: vector X, angle a
//   To rotate this vector about axe X we should apply the following
//   operation:  X'=X*Rx, where Rx - is matrix of rotation
//        [ 1 0      0     0 ]
//        [ 0 cos a  sin a 0 ]
//     Rx=[ 0 -sin a cos a 0 ]
//        [ 0 0      0     1 ]
//   Applying this operation to every point of the given object we
//   rotate it.
//
//////////////////////////////////////////////////////////////////////////////

#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <math.h>
#include <dos.h>

#define Pi 3.1415926536

enum Action{move,draw};

struct Point3D
{
 float x;
 float y;
 float z;
 Action action;
};

// this function initializes graphics mode
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void init_gr(void)
{
       /* request autodetection */
       int gdriver = DETECT, gmode, errorcode;

       /* initialize graphics mode */
       initgraph(&gdriver, &gmode, "");

       /* read result of initialization */
       errorcode = graphresult();

       if (errorcode != grOk)    /* an error occurred */
       {
              printf("Graphics error: %s\n", grapherrormsg(errorcode));
              printf("Press any key to halt:");
              getch();
              exit(1);               /* return with error code */
       }
}

// this function shuts graphics mode down
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void end_gr(void)
{
 closegraph();
}

// this function moves CP to (x,y) position
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void MoveTo(int x, int y)
{
 moveto(x,y);
}

// this function draws a line to (x,y) position
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void LineTo(int x, int y)
{
 lineto(x,y);
}

void draw3Dobject(Point3D *object, int N, float rho, float theta,
                 float phi, float dist_to_screen, int xshift, int yshift)
{
 int x,y;
 float xe,ye,ze,costh,sinph,cosph,sinth,v11,v12,v13,v21,v22,v32,v33,v23,v43;

 // calculating coefficients
 costh=cos(theta);
 sinth=sin(theta);
 cosph=cos(phi);
 sinph=sin(phi);
 v11=-sinth; v12=-cosph*costh; v13=-sinph*costh;
 v21=costh;  v22=-cosph*sinth; v23=-sinph*sinth;
                     v32=sinph;             v33=-cosph;
                                                    v43=rho;
 for (int i=0;i<N;i++)
 {
        // calculating eye coordinates
        xe=v11*(object+i)->x+v21*(object+i)->y;
        ye=v12*(object+i)->x+v22*(object+i)->y+v32*(object+i)->z;
        ze=v13*(object+i)->x+v23*(object+i)->y+v33*(object+i)->z+v43;

        // calculating screen coordinates
        x=dist_to_screen*xe/ze+xshift;
        y=dist_to_screen*ye/ze+yshift;

       // drawing
        if((object+i)->action==move)
             MoveTo(x,y);
        else
             LineTo(x,y);
 }
}

void RotateX(Point3D *object, int n, float angle)
{
 float cosa,sina,y,z;

 cosa=cos(angle);
 sina=sin(angle);
 for(int i=0;i<n;i++)
 {
        y=(object+i)->y*cosa-(object+i)->z*sina;
        z=(object+i)->y*sina+(object+i)->z*cosa;
        (object+i)->y=y;
        (object+i)->z=z;
 }
}

void RotateY(Point3D *object, int n, float angle)
{
 float cosa,sina,x,z;

 cosa=cos(angle);
 sina=sin(angle);
 for(int i=0;i<n;i++)
 {
        x=(object+i)->x*cosa+(object+i)->z*sina;
        z=-(object+i)->x*sina+(object+i)->z*cosa;
        (object+i)->x=x;
        (object+i)->z=z;
 }
}

void RotateZ(Point3D *object, int n, float angle)
{
 float cosa,sina,x,y;

 cosa=cos(angle);
 sina=sin(angle);
 for(int i=0;i<n;i++)
 {
        x=(object+i)->x*cosa-(object+i)->y*sina;
        y=(object+i)->x*sina+(object+i)->y*cosa;
        (object+i)->x=x;
        (object+i)->y=y;
 }
}

int main(void)
{
 Point3D thetr[]={{100,100,100,move},
                             {100,200,100,draw},
                             {200,100,100,draw},
                             {100,100,100,draw},
                             {100,100,200,draw},
                             {200,100,100,draw},
                             {100,100,200,move},
                             {100,200,100,draw}};

 Point3D cube[]={{-50,-50,-50,move},
                             {-50,50,-50,draw},
                             {-50,50,50,draw},
                             {50,50,50,draw},
                             {50,50,-50,draw},
                             {50,-50,-50,draw},
                             {50,-50,50,draw},
                             {-50,-50,50,draw},
                             {-50,50,50,draw},
                             {-50,-50,50,move},
                             {-50,-50,-50,draw},
                             {50,-50,-50,draw},
                             {50,50,-50,move},
                             {-50,50,-50,draw},
                             {50,-50,50,move},
                             {50,50,50,draw}};

 int N=sizeof(thetr)/sizeof(Point3D);
 int M=sizeof(cube)/sizeof(Point3D);
 float rho=1500,theta=Pi/4,phi=-3*Pi/4,dist_to_screen=700;
 int xshift=300, yshift=150,xshift1=200,yshift1=200;

 // initializing graphics mode
 init_gr();

 /* examples */
 while (!kbhit())
 {
         RotateX(cube,M,Pi/24);
         RotateY(cube,M,Pi/24);
         RotateZ(cube,M,Pi/24);
         RotateY(thetr,N,Pi/30);
         setcolor(12);
         draw3Dobject(thetr,N,rho,theta,phi,dist_to_screen,xshift,yshift);
         draw3Dobject(cube,M,rho,theta,phi,dist_to_screen,xshift1,yshift1);
         setcolor(0);
         delay(35);
         draw3Dobject(thetr,N,rho,theta,phi,dist_to_screen,xshift,yshift);
         draw3Dobject(cube,M,rho,theta,phi,dist_to_screen,xshift1,yshift1);
 }

 /* clean up */
 getch();
 end_gr();

 return 0;
}

PM WWW ICQ   Вверх
podval
Дата 22.12.2004, 09:51 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Где я? Кто я?
****


Профиль
Группа: Экс. модератор
Сообщений: 3094
Регистрация: 25.3.2002
Где: СПб

Репутация: 18
Всего: 62



Рисование куба

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Generating and drawing cube
//  (c) Johna Smith, 1996
//
//  Method description:
//    Cube is one of simplest figures in stereometry.
//    We just need to generate 'n' squares parallel to X,Y and Z axes
//
//////////////////////////////////////////////////////////////////////////////

#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <math.h>
#include <dos.h>

#define Pi 3.1415926536

enum Action{move,draw};

struct Point3D
{
 int x;
 int y;
 int z;
 Action action;
};

// this function initializes graphics mode
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void init_gr(void)
{
 /* request autodetection */
 int gdriver = DETECT, gmode, errorcode;

 /* initialize graphics mode */
 initgraph(&gdriver, &gmode, "");

 /* read result of initialization */
 errorcode = graphresult();

 if (errorcode != grOk)    /* an error occurred */
 {
    printf("Graphics error: %s\n", grapherrormsg(errorcode));
    printf("Press any key to halt:");
    getch();
    exit(1);               /* return with error code */
 }
}

// this function shuts graphics mode down
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void end_gr(void)
{
 closegraph();
}

// this function moves CP to (x,y) position
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void MoveTo(int x, int y)
{
 moveto(x,y);
}

// this function draws a line to (x,y) position
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void LineTo(int x, int y)
{
 lineto(x,y);
}

void draw3Dobject(Point3D *object, int N, float rho, float theta,
                 float phi, float dist_to_screen, int xshift, int yshift)
{
 int x,y;
 float xe,ye,ze,costh,sinph,cosph,sinth,v11,v12,v13,v21,v22,v32,v33,v23,v43;

 // calculating coefficients
 costh=cos(theta);
 sinth=sin(theta);
 cosph=cos(phi);
 sinph=sin(phi);
 v11=-sinth; v12=-cosph*costh; v13=-sinph*costh;
 v21=costh;  v22=-cosph*sinth; v23=-sinph*sinth;
             v32=sinph;        v33=-cosph;
                               v43=rho;
 for (int i=0;i<N;i++)
 {
    // calculating eye coordinates
    xe=v11*(object+i)->x+v21*(object+i)->y;
    ye=v12*(object+i)->x+v22*(object+i)->y+v32*(object+i)->z;
    ze=v13*(object+i)->x+v23*(object+i)->y+v33*(object+i)->z+v43;
 
    // calculating screen coordinates
    x=dist_to_screen*xe/ze+xshift;
    y=dist_to_screen*ye/ze+yshift;

    // drawing
    if((object+i)->action==move)
      MoveTo(x,y);
    else
      LineTo(x,y);
 }
}

int main(void)
{
 const int n=4; // number of cubes segments +1
 Point3D cube[15*n]; // coordinates for cubes points
 float rho=1900,theta=Pi/3,phi=2*Pi/3,dist_to_screen=600; // view point
 int xshift=300, yshift=140; // picture offset
 float side=300; // cubes parameters
 float delta;// auxulary variable

 // initializing graphics mode
 init_gr();

 // generating cube
 delta=side/(n-1);
 for (int i=0;i<n;i++)
 {
   for(int j=i*5;j<i*5+5;j++)
   {
     cube[j].x=i*delta;
     cube[j].action=draw;
   }
   cube[i*5].y=0;
   cube[i*5].z=0;
   cube[i*5].action=move;
   cube[i*5+1].y=side;
   cube[i*5+1].z=0;
   cube[i*5+2].y=side;
   cube[i*5+2].z=side;
   cube[i*5+3].y=0;
   cube[i*5+3].z=side;
   cube[i*5+4].y=0;
   cube[i*5+4].z=0;
 }
 int c=5*n;
 for (i=0;i<n;i++)
 {
   for(int j=i*5;j<i*5+5;j++)
   {
     cube[c+j].y=i*delta;
     cube[c+j].action=draw;
   }
   cube[c+i*5].x=0;
   cube[c+i*5].z=0;
   cube[c+i*5].action=move;
   cube[c+i*5+1].x=side;
   cube[c+i*5+1].z=0;
   cube[c+i*5+2].x=side;
   cube[c+i*5+2].z=side;
   cube[c+i*5+3].x=0;
   cube[c+i*5+3].z=side;
   cube[c+i*5+4].x=0;
   cube[c+i*5+4].z=0;
 }
 c=10*n;
 for (i=0;i<n;i++)
 {
   for(int j=i*5;j<i*5+5;j++)
   {
      cube[c+j].z=i*delta;
      cube[c+j].action=draw;
   }
   cube[c+i*5].y=0;
   cube[c+i*5].x=0;
   cube[c+i*5].action=move;
   cube[c+i*5+1].y=side;
   cube[c+i*5+1].x=0;
   cube[c+i*5+2].y=side;
   cube[c+i*5+2].x=side;
   cube[c+i*5+3].y=0;
   cube[c+i*5+3].x=side;
   cube[c+i*5+4].y=0;
   cube[c+i*5+4].x=0;
 }

 // drawing
 draw3Dobject(cube,15*n,rho,theta,phi,dist_to_screen,xshift,yshift);

 /* clean up */
 getch();
 end_gr();

 return 0;
}



Рисование тора

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Generating and drawing torus
//  (c) Johna Smith, 1996
//
//  Method description:
//    Torus has two main circles, which are described by
//   two systems of eqations:
//    x=Rcos(a)     x=R+rcos(b)
//    y=Rsin(a)     y=0
//    z=0           z=rsin(b)
//    By generating this circles (approximating by polygons) we can get torus
//
//////////////////////////////////////////////////////////////////////////////

#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <math.h>
#include <dos.h>

#define Pi 3.1415926536

enum Action{move,draw};

struct Point3D
{
 int x;
 int y;
 int z;
 Action action;
};

// this function initializes graphics mode
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void init_gr(void)
{
  /* request autodetection */
  int gdriver = DETECT, gmode, errorcode;

  /* initialize graphics mode */
  initgraph(&gdriver, &gmode, "");

  /* read result of initialization */
  errorcode = graphresult();

  if (errorcode != grOk)    /* an error occurred */
  {
     printf("Graphics error: %s\n", grapherrormsg(errorcode));
     printf("Press any key to halt:");
     getch();
     exit(1);               /* return with error code */
  }
}

// this function shuts graphics mode down
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void end_gr(void)
{
 closegraph();
}

// this function moves CP to (x,y) position
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void MoveTo(int x, int y)
{
 moveto(x,y);
}

// this function draws a line to (x,y) position
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void LineTo(int x, int y)
{
 lineto(x,y);
}

void draw3Dobject(Point3D *object, int N, float rho, float theta,
                 float phi, float dist_to_screen, int xshift, int yshift)
{
 int x,y;
 float xe,ye,ze,costh,sinph,cosph,sinth,v11,v12,v13,v21,v22,v32,v33,v23,v43;

 // calculating coefficients
 costh=cos(theta);
 sinth=sin(theta);
 cosph=cos(phi);
 sinph=sin(phi);
 v11=-sinth; v12=-cosph*costh; v13=-sinph*costh;
 v21=costh;  v22=-cosph*sinth; v23=-sinph*sinth;
             v32=sinph;        v33=-cosph;
                               v43=rho;
 for (int i=0;i<N;i++)
 {
     // calculating eye coordinates
     xe=v11*(object+i)->x+v21*(object+i)->y;
     ye=v12*(object+i)->x+v22*(object+i)->y+v32*(object+i)->z;
     ze=v13*(object+i)->x+v23*(object+i)->y+v33*(object+i)->z+v43;

     // calculating screen coordinates
     x=dist_to_screen*xe/ze+xshift;
     y=dist_to_screen*ye/ze+yshift;
 
     // drawing
     if((object+i)->action==move)
       MoveTo(x,y);
     else
       LineTo(x,y);
 }
}

int main(void)
{
 const int n=20;  // number of torus' segments
 Point3D torus[2*n*(n+1)]; // coordinates for torus' points
 float rho=1800,theta=0,phi=3*Pi/4,dist_to_screen=600; // view point
 int xshift=300, yshift=250; // picture offset
 float delta=2.0*Pi/n, r=75, R=300; // torus' parameters
 float alpha,cosa,sina,beta,x; // auxulary variables

 // initializing graphics mode
 init_gr();

 // generating torus
 for (int i=0;i<n;i++)
 {
    alpha=i*delta;
    cosa=cos(alpha);
    sina=sin(alpha);
    for (int j=0;j<n+1;j++)
    {
      beta=j*delta;
      x=R+r*cos(beta);
      torus[i*(n+1)+j].x=cosa*x;
      torus[i*(n+1)+j].y=sina*x;
      torus[i*(n+1)+j].z=r*sin(beta);
      torus[i*(n+1)+j].action=((i==0 && j==0)?move:draw);
    }
 }
 int c=n*n+n;
 for (i=0;i<n;i++)
 {
    beta=i*delta;
    x=R+r*cos(beta);
    for (int j=0;j<n+1;j++)
    {
      alpha=j*delta;
      cosa=cos(alpha);
      sina=sin(alpha);
      torus[c+i*(n+1)+j].x=cosa*x;
      torus[c+i*(n+1)+j].y=sina*x;
      torus[c+i*(n+1)+j].z=r*sin(beta);
      torus[c+i*(n+1)+j].action=draw;
    }
 }

 // drawing
 draw3Dobject(torus,2*n*(n+1),rho,theta,phi,dist_to_screen,xshift,yshift);

 /* clean up */
 getch();
 end_gr();

 return 0;
}

PM WWW ICQ   Вверх
podval
Дата 22.12.2004, 10:02 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Где я? Кто я?
****


Профиль
Группа: Экс. модератор
Сообщений: 3094
Регистрация: 25.3.2002
Где: СПб

Репутация: 18
Всего: 62



Рисование полусферы

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Generating and drawing semisphere
//  (c) Johna Smith, 1996
//
//  Method description:
//    Hemisphere is described by following eqation:
//       2    2    2
//      x  + y  + z  = 1,    -1<=z<=0
//
//    By generating this points with step 'delta' we can approximate hemisphere
//
//////////////////////////////////////////////////////////////////////////////

#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <math.h>
#include <dos.h>

#define Pi 3.1415926536

enum Action{move,draw};

struct Point3D
{
 int x;
 int y;
 int z;
 Action action;
};

// this function initializes graphics mode
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void init_gr(void)
{
  /* request autodetection */
  int gdriver = DETECT, gmode, errorcode;

  /* initialize graphics mode */
  initgraph(&gdriver, &gmode, "");

  /* read result of initialization */
  errorcode = graphresult();

  if (errorcode != grOk)    /* an error occurred */
  {
     printf("Graphics error: %s\n", grapherrormsg(errorcode));
     printf("Press any key to halt:");
     getch();
     exit(1);               /* return with error code */
  }
}

// this function shuts graphics mode down
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void end_gr(void)
{
 closegraph();
}

// this function moves CP to (x,y) position
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void MoveTo(int x, int y)
{
 moveto(x,y);
}

// this function draws a line to (x,y) position
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void LineTo(int x, int y)
{
 lineto(x,y);
}

void draw3Dobject(Point3D *object, int N, float rho, float theta,
                   float phi, float dist_to_screen, int xshift, int yshift)
{
 int x,y;
 float xe,ye,ze,costh,sinph,cosph,sinth,v11,v12,v13,v21,v22,v32,v33,v23,v43;

 // calculating coefficients
 costh=cos(theta);
 sinth=sin(theta);
 cosph=cos(phi);
 sinph=sin(phi);
 v11=-sinth; v12=-cosph*costh; v13=-sinph*costh;
 v21=costh;  v22=-cosph*sinth; v23=-sinph*sinth;
             v32=sinph;        v33=-cosph;
                               v43=rho;
 for (int i=0;i<N;i++)
 {
    // calculating eye coordinates
    xe=v11*(object+i)->x+v21*(object+i)->y;
    ye=v12*(object+i)->x+v22*(object+i)->y+v32*(object+i)->z;
    ze=v13*(object+i)->x+v23*(object+i)->y+v33*(object+i)->z+v43;

    // calculating screen coordinates
    x=dist_to_screen*xe/ze+xshift;
    y=dist_to_screen*ye/ze+yshift;

    // drawing
    if((object+i)->action==move)
      MoveTo(x,y);
    else
      LineTo(x,y);
 }
}

int main(void)
{
 const int n=10;  // number of hemispheres segments
 Point3D hemisphere[8*n*n+n]; // coordinates for hemispheres points
 float rho=1800,theta=Pi,phi=3*Pi/4,dist_to_screen=600; // view point
 int xshift=300, yshift=250; // picture offset
 float delta=Pi/(2*n), R=300; // hemisphere parameters
 float alpha,cosa,sina,beta,cosb,sinb; // auxulary variables

 // initializing graphics mode
 init_gr();

 // generating semisphere
 for (int i=0;i<4*n;i++)
 {
    alpha=i*delta;
    cosa=cos(alpha);
    sina=sin(alpha);
    for (int j=0;j<n;j++)
    {
      beta=j*delta;
      sinb=sin(beta);
      cosb=cos(beta);
      hemisphere[i*n+j].x=R*cosa*sinb;
      hemisphere[i*n+j].y=R*sina*sinb;
      hemisphere[i*n+j].z=-R*cosb;
      hemisphere[i*n+j].action=(j==0?move:draw);
    }
 }
 int c=4*n*n;
 for (i=0;i<n;i++)
 {
    beta=i*delta;
    sinb=sin(beta);
    cosb=cos(beta);
    for (int j=0;j<4*n+1;j++)
    {
      alpha=j*delta;
      cosa=cos(alpha);
      sina=sin(alpha);
      hemisphere[c+i*(4*n+1)+j].x=R*cosa*sinb;
      hemisphere[c+i*(4*n+1)+j].y=R*sina*sinb;
      hemisphere[c+i*(4*n+1)+j].z=-R*cosb;
      hemisphere[c+i*(4*n+1)+j].action=(j==0?move:draw);
    }
 }

 // drawing
 draw3Dobject(hemisphere,8*n*n+n,rho,theta,phi,dist_to_screen,xshift,yshift);

 /* clean up */
 getch();
 end_gr();

 return 0;
}




Вращение фигуры в плоскости

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Rotations in 2 dimensions
//  (c) Johna Smith, 1996
//
//  Method description:
//    There is the following formulas for rotating in 2 dimensions:
//      x'=x0+(x-x0)*cos(phi)-(y-y0)*sin(phi)
//      y'=y0+(x-x0)*sin(phi)+(y-y0)*cos(phi)
//    To rotate the figure we should rotate each of its points
//
//////////////////////////////////////////////////////////////////////////////

#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <math.h>

#define Pi 3.1415926536

// this function initializes graphics mode
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void init_gr(void)
{
  /* request autodetection */
  int gdriver = DETECT, gmode, errorcode;

  /* initialize graphics mode */
  initgraph(&gdriver, &gmode, "");

  /* read result of initialization */
  errorcode = graphresult();

  if (errorcode != grOk)    /* an error occurred */
  {
     printf("Graphics error: %s\n", grapherrormsg(errorcode));
     printf("Press any key to halt:");
     getch();
     exit(1);               /* return with error code */
  }
}

// this function shuts graphics mode down
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void end_gr(void)
{
 closegraph();
}

// this function moves CP to (x,y) position
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void MoveTo(int x, int y)
{
 moveto(x,y);
}

// this function draws a line to (x,y) position
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void LineTo(int x, int y)
{
 lineto(x,y);
}

const N=6; // number of points in the figure

// coordinates of all given points
enum actions {MOVE,DRAW};
struct
{
 actions action;
 int x;
 int y;
} figure[N]={{MOVE,360,270},{DRAW,360,260},{DRAW,355,260},{DRAW,360,250},
    {DRAW,365,260},{DRAW,360,260}};

int x0,y0,dx,dy;
float phi;

int main(void)
{
 // initializing graphics mode
 init_gr();

 // rotating about (x0,y0)
 x0=300;
 y0=260;
 // by 10 degrees
 phi=45.0*Pi/180.0;

 // main loop
 for(int i=0;i<8;i++)
 {
   // rotating the figure
   for (int j=0;j<N;j++)
   {
     dx=figure[j].x-x0;
     dy=figure[j].y-y0;
     figure[j].x=x0+dx*cos(phi)-dy*sin(phi);
     figure[j].y=y0+dx*sin(phi)+dy*cos(phi);
   }
   // drawing rotated figure
 for (j=0;j<N;j++)
     if (figure[j].action==MOVE)
       MoveTo(figure[j].x,figure[j].y);
     else
       LineTo(figure[j].x,figure[j].y);
 }

 // clean up
 getch();
 end_gr();

 return 0;
}

PM WWW ICQ   Вверх
podval
Дата 22.12.2004, 10:13 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Где я? Кто я?
****


Профиль
Группа: Экс. модератор
Сообщений: 3094
Регистрация: 25.3.2002
Где: СПб

Репутация: 18
Всего: 62



Рисование линии (по Брезенхэму)

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Bresengham line drawing
//  (c) Johna Smith, 1996
//
//  Method description:
//    Determine  dy=(y2-y1), dx=(x2-x1)
//    We plot first point of the line and increase errors of plotting
//    (xerr and yerr) by dx and dy respectively. If the error is greater
//    than largest from dx and dy then we should correct next point and
//    shift it to 1 pixel by that axe where error was too big.
//
//  ! This program is NOT optimized for best performance !
//  To do so don't use putpixel function - change bytes in video memory directly.
//
//////////////////////////////////////////////////////////////////////////////

#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <math.h>

// this function initializes graphics mode
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void init_gr(void)
{
  /* request autodetection */
  int gdriver = DETECT, gmode, errorcode;

  /* initialize graphics mode */
  initgraph(&gdriver, &gmode, "");

  /* read result of initialization */
  errorcode = graphresult();

  if (errorcode != grOk)    /* an error occurred */
  {
      printf("Graphics error: %s\n", grapherrormsg(errorcode));
      printf("Press any key to halt:");
      getch();
      exit(1);               /* return with error code */
  }
}

// this function shuts graphics mode down
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void end_gr(void)
{
 closegraph();
}

// this function puts pixel on the screen in (x,y) position using color 'color'
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void PutPixel(int x, int y, int color)
{
 putpixel(x,y,color);
}

void BLine(int x1,int y1,int x2, int y2, int color)
{
 int delta_x,delta_y,incx,incy,t,distance;
 int xerr=0,yerr=0;

 // determine dx and dy
 delta_x=x2-x1;
 delta_y=y2-y1;

 // determine steps by x and y axes (it will be +1 if we move in forward
 // direction and -1 if we move in backward direction
 if (delta_x>0) incx=1;
 else if (delta_x==0) incx=0;
 else incx=-1;

 if (delta_y>0) incy=1;
 else if (delta_y==0) incy=0;
 else incy=-1;

 delta_x=abs(delta_x);
 delta_y=abs(delta_y);

 // select largest from deltas and use it as a main distance
 if (delta_x>delta_y) distance=delta_x;
 else distance=delta_y;

 for (t=0;t<=distance+1;t++)
 {
   PutPixel(x1,y1,color);
   // increasing error
   xerr+=delta_x;
   yerr+=delta_y;
   // if error is too big then we should decrease it by changing
   // coordinates of the next plotting point to make it closer
   // to the true line
   if(xerr>distance)
   {
     xerr-=distance;
     x1+=incx;
   }
   if (yerr>distance)
   {
     yerr-=distance;
     y1+=incy;
   }
 }
}

int main(void)
{
 // initializing graphics mode
 init_gr();

 /* examples */
 BLine(0, 0, 640, 480,15);
 BLine(320, 0, 320, 480,10);
 BLine(0, 240, 640, 240,11);
 BLine(0, 480, 640, 0,12);
 BLine(320, 11, 10, 5,13);
 BLine(320, 11, 630, 5,13);

 /* clean up */
 getch();
 end_gr();
 
 return 0;
}



Рисование окружности (по Брезенхэму)

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Bresengham circle drawing
//  (c) Johna Smith, 1996
//
//  Method description:
//    In this algorithm all floating point math changed to sequences
//  of additions and substractions. The main idea of this algorithm
//  is to increase x and y by the value of the error between them.
//
//  ! This program is NOT optimized for best performance !
//  To do so don't use putpixel function - change bytes in video memory directly.
//
//////////////////////////////////////////////////////////////////////////////

#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <math.h>

// this function initializes graphics mode
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void init_gr(void)
{
  /* request autodetection */
  int gdriver = DETECT, gmode, errorcode;

  /* initialize graphics mode */
  initgraph(&gdriver, &gmode, "");

  /* read result of initialization */
  errorcode = graphresult();

  if (errorcode != grOk)    /* an error occurred */
  {
     printf("Graphics error: %s\n", grapherrormsg(errorcode));
     printf("Press any key to halt:");
     getch();
     exit(1);               /* return with error code */
  }
}

// this function shuts graphics mode down
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void end_gr(void)
{
 closegraph();
}

// this function puts pixel on the screen in (x,y) position using color 'color'
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void PutPixel(int x, int y, int color)
{
 putpixel(x,y,color);
}


float const ratio=1.0; // you can change this to draw ellipses

// This function plots points that belongs to the circle
// It recieves offsets from center for the fist quadrant
// and plots symmetrical points in all four quadrants
void plot_circle(int x,int y, int x_center, int y_center, int color)
{
 int x_start,y_start,x_end,y_end,x1,y1;

 // the distanse between start and end can be greater than 1 if ratio!=1
 y_start=y*ratio;
 y_end=(y+1)*ratio;
 x_start=x*ratio;
 x_end=(x+1)*ratio;

 for (x1=x_start;x1<x_end;++x1)
 {
   // plot points in all four quadrants
   PutPixel(x1+x_center,y+y_center,color);
   PutPixel(x1+x_center,y_center-y,color);
   PutPixel(x_center-x1,y+y_center,color);
   PutPixel(x_center-x1,y_center-y,color);
 }

 for (y1=y_start;y1<y_end;++y1)
 {
   // plot points in all four quadrants
   PutPixel(y1+x_center,x+y_center,color);
   PutPixel(y1+x_center,y_center-x,color);
   PutPixel(x_center-y1,x+y_center,color);
   PutPixel(x_center-y1,y_center-x,color);
 }
}

// This is main function that draws circle using function

void Circle(int x1,int y1,int radius, int color)
{
 int x,y,delta;

//     Y    *              we start from * and increase x step by step
//          |              decreasing y when needed
//          |
//          |
// --------------------
//          |         X
//          |
//          |
//          |
 y=radius;
 delta=3-2*radius; // delta is an error
 // calculate values for first quadrant
 for (x=0;x<y;x++) // x is a main axe
 {
   // plot points symmetrically in all quadrants
   plot_circle(x,y,x1,y1,color);
   if (delta<0) delta+=4*x+6;
   else
   {
     delta+=4*(x-y)+10;
     y--; // it's time to decrease y
   }
 }
 x=y;
 if (y!=0) plot_circle(x,y,x1,y1,color);
}

int main(void)
{
 // initializing graphics mode
 init_gr();

 /* examples */
 Circle(200,200,100,14);
 Circle(300,200,100,15);
 Circle(400,200,100,13);
 Circle(250,100,100,12);
 Circle(350,100,100,11);
 Circle(50,400,25,2);
 Circle(500,400,25,2);

 /* clean up */
 getch();
 end_gr();
 return 0;
}


PM WWW ICQ   Вверх
podval
Дата 22.12.2004, 10:25 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Где я? Кто я?
****


Профиль
Группа: Экс. модератор
Сообщений: 3094
Регистрация: 25.3.2002
Где: СПб

Репутация: 18
Всего: 62



Сглаживание кривой В-сплайном

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Curve fitting using B-splines
//  (c) Johna Smith, 1996
//
//  Method description:
//    We are drawing lines between points using the following formulas:
//    x(t)=((a3*t+a2)*t+a1)*t+a0
//    y(t)=((b3*t+b2)*t+b1)*t+b0
//    t=0..1
//    Look program for formulas for coefficients ai,bi
//    These coefficients depends on coordinates of current point,
//    previous one, next and next-next ones.
//
//////////////////////////////////////////////////////////////////////////////

#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <math.h>

// this function initializes graphics mode
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void init_gr(void)
{
  /* request autodetection */
  int gdriver = DETECT, gmode, errorcode;

  /* initialize graphics mode */
  initgraph(&gdriver, &gmode, "");

  /* read result of initialization */
  errorcode = graphresult();

  if (errorcode != grOk)    /* an error occurred */
  {
     printf("Graphics error: %s\n", grapherrormsg(errorcode));
     printf("Press any key to halt:");
     getch();
     exit(1);               /* return with error code */
  }
}

// this function shuts graphics mode down
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void end_gr(void)
{
 closegraph();
}

// this function moves CP to (x,y) position
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void MoveTo(int x, int y)
{
 moveto(x,y);
}

// this function draws a line to (x,y) position
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void LineTo(int x, int y)
{
 lineto(x,y);
}

// this function draws a line from (x1,y1) to (x2,y2)
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void Line(int x1, int y1, int x2, int y2)
{
 line(x1,y1,x2,y2);
}


const N=21; // number of points
const M=300.0; // number of steps between two points

// coordinates of all given points
int x[N]={50,25,50,125,200,225,275,475,590,615,615,615,600,475,275,225,200,125,50,25,50};
int y[N]={140,100,60,40,70,90,85,75,80,85,100,115,120,125,115,110,130,160,140,100,60};

// coefficients
float t,xA,xB,xC,xD,yA,yB,yC,yD,a0,a1,a2,a3,b0,b1,b2,b3;
int n,i,j,first;

int main(void)
{
 // initializing graphics mode
 init_gr();

  /* mark the given points */
  for (i=0;i<N;i++)
  {
    Line(x[i]-4,y[i]-4,x[i]+4,y[i]+4);
    Line(x[i]+4,y[i]-4,x[i]-4,y[i]+4);
  }

  /* main loop */
  first=1;
  for(i=1;i<N-2;i++)
  {
    // calculating coefficients
    xA=x[i-1]; xB=x[i]; xC=x[i+1]; xD=x[i+2];
    yA=y[i-1]; yB=y[i]; yC=y[i+1]; yD=y[i+2];
    a3=(-xA+3*(xB-xC)+xD)/6.0;  b3=(-yA+3*(yB-yC)+yD)/6.0;
    a2=(xA-2*xB+xC)/2.0;        b2=(yA-2*yB+yC)/2.0;
    a1=(xC-xA)/2.0;             b1=(yC-yA)/2.0;
    a0=(xA+4*xB+xC)/6.0;        b0=(yA+4*yB+yC)/6.0;
    for (j=0;j<M;j++) // drawing curve between two given points
    {
      t=(float)j/(float)M;
      if (first)
      {
        first=0;
        MoveTo(((a3*t+a2)*t+a1)*t+a0,((b3*t+b2)*t+b1)*t+b0);
      } else LineTo(((a3*t+a2)*t+a1)*t+a0,((b3*t+b2)*t+b1)*t+b0);
    }
  }

  /* clean up */
  getch();
  end_gr();
 
  return 0;
}



Постепенное затемнение

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Fade to black (slowly turning the light off)
//  (c) Johna Smith, 1996
//
//  Method description:
//    We need only to decrease Red, Green and Blue components for each color
//    in palette. For example, if Red component of the first color was
//    initially 60 and we want to turn the light off in 30 steps we should
//    decrease Red component by 60/30=2 by step.
//  To increase productivity of this program you shouldn't use standart
//  BGI functions. Use direct methods instead.
//
//////////////////////////////////////////////////////////////////////////////

#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <math.h>
#include <dos.h>

// this function initializes graphics mode
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void init_gr(void)
{
  /* request autodetection */
  int gdriver = DETECT, gmode, errorcode;

  /* initialize graphics mode */
  initgraph(&gdriver, &gmode, "");

  /* read result of initialization */
  errorcode = graphresult();

  if (errorcode != grOk)    /* an error occurred */
  {
     printf("Graphics error: %s\n", grapherrormsg(errorcode));
     printf("Press any key to halt:");
     getch();
     exit(1);               /* return with error code */
  }
}

// this function shuts graphics mode down
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void end_gr(void)
{
 closegraph();
}

// this function set filling style
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void SetFillStyle(int pattern,int color)
{
 setfillstyle(pattern,color);
}

// this function draws a bar
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void Bar(int x1, int y1, int x2, int y2)
{
 bar(x1,y1,x2,y2);
}

// this function sets palette entry using RGB color coding
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void SetRGBPalette(int colornum, int red, int green, int blue)
{
 setrgbpalette(colornum,red,green,blue);
}

// this function reads palette
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void GetPalette(struct palettetype far *palette)
{
 getpalette(palette);
}

#define N 30 // steps of fading to black

struct palettetype pal;
struct {int R;int G;int B;} colors[16];

int main(void)
{
 // initializing graphics mode
 init_gr();

 // creating palette
 GetPalette(&pal);
 for(int i=0;i<pal.size-1;i++)
 {
    colors[i+1].R=0;
    colors[i+1].G=30-2*i;
    colors[i+1].B=15+i*2;
    SetRGBPalette(pal.colors[i+1],colors[i+1].R,colors[i+1].G,colors[i+1].B);
 }

 // drawing picture
 for (i=1;i<16;i++)
 {
    SetFillStyle(SOLID_FILL,i);
    Bar((i-1)*43,0,i*43,479);
 }

 // fading to balck
 for (int j=0;j<N;j++)
 {
    //delay(50);
    for (i=1;i<pal.size;i++)
       SetRGBPalette(pal.colors[i],
  colors[i].R*(1-(float)j/N),
         colors[i].G*(1-(float)j/N),
         colors[i].B*(1-(float)j/N));
 }

 // and back to the light
 for (j=0;j<N;j++)
 {
    //delay(50);
    for (i=1;i<pal.size;i++)
       SetRGBPalette(pal.colors[i],
         colors[i].R*(float)j/N,
         colors[i].G*(float)j/N,
         colors[i].B*(float)j/N);
 }

 /* clean up */
 getch();
 end_gr();

 return 0;
}

PM WWW ICQ   Вверх
podval
Дата 22.12.2004, 10:35 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Где я? Кто я?
****


Профиль
Группа: Экс. модератор
Сообщений: 3094
Регистрация: 25.3.2002
Где: СПб

Репутация: 18
Всего: 62



Заливка замкнутой области

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Filling closed area using given color
//  (c) Johna Smith, 1996
//
//  Method description:
//    1) Fill all pixels on the current line
//    2) Call FloodFill recursively for two remote points to reduce
//       the depth of the recursion
//    3) Call FloodFill recursively for all points on two nearest
//       horizontal lines
//  ! This program is NOT optimized for best performance !
//  To do so don't use PutPixel & GetPixel function -
//  change bytes in video memory directly.
//
//////////////////////////////////////////////////////////////////////////////

#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>

// this function initializes graphics mode
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void init_gr(void)
{
  /* request autodetection */
  int gdriver = DETECT, gmode, errorcode;

  /* initialize graphics mode */
  initgraph(&gdriver, &gmode, "");

  /* read result of initialization */
  errorcode = graphresult();

  if (errorcode != grOk)    /* an error occurred */
  {
     printf("Graphics error: %s\n", grapherrormsg(errorcode));
     printf("Press any key to halt:");
     getch();
     exit(1);               /* return with error code */
  }
}

// this function shuts graphics mode down
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void end_gr(void)
{
 closegraph();
}

// this function puts pixel on the screen in (x,y) position using color 'color'
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void PutPixel(int x, int y, int color)
{
 putpixel(x,y,color);
}

// this function gets color of pixel in (x,y) position
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

int GetPixel(int x, int y)
{
 return getpixel(x,y);
}

// this function gets maximum horizontal coordinate
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

int GetMaxX(void)
{
 return getmaxx();
}

// this function gets maximum vertical coordinate
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

int GetMaxY(void)
{
 return getmaxy();
}

void FloodFill(int x, int y,int fill_color, int border_color)
{
 int x_left,x_right,YY,i;
 int XMAX,YMAX;

 XMAX=GetMaxX();
 YMAX=GetMaxY();

 // Light as many pixels as possible on line y
 // and determine x_left and x_right
 x_left=x_right=x;
 while (GetPixel(x_left,y)!=border_color && x_left>0)
 {
    PutPixel(x_left,y,fill_color);
    x_left--;
 }
 x_right++;
 while (GetPixel(x_right,y)!=border_color && x_right<XMAX)
 {
    PutPixel(x_right,y,fill_color);
    x_right++;
 }
 // Recursive calls of FloodFill for two remote points
 x=(x_right+x_left)>>1; //shifting means division by 2
 for(i=-1;i<=1;i+=2)
 {
    YY=y;
    while (GetPixel(x,YY)!=border_color && YY<YMAX && YY>0) YY+=i;
    YY=(y+YY)>>1;
    if (GetPixel(x,YY)!=border_color && GetPixel(x,YY)!=fill_color) FloodFill(x,YY,fill_color,border_color);
 }
 // Recursive calls for all "dark" (not filled) pixels next
 // to the line y (with x values between x_left and x_right
 for(YY=y-1;YY<=y+1;YY+=2)
 {
   x=x_left+1;
   while (x<x_right && YY>0 && YY<YMAX)
   {
     if (GetPixel(x,YY)!=border_color && GetPixel(x,YY)!=fill_color) FloodFill(x,YY,fill_color,border_color);
     x++;
   }
 }
}

int main(void)
{
  // initializing graphics mode
  init_gr();

  // drawing area to fill
  moveto(520,90); lineto(520,190); lineto(470,240);
  lineto(520,290); lineto(520,390);
  lineto(320,315); lineto(120,390);
  lineto(120,290); lineto(170,240);
  lineto(120,190); lineto(120, 90);
  lineto(270,90); lineto(270,120);
  lineto(170,120); lineto(170,150);
  lineto(470,150); lineto(470,120);
  lineto(370,120); lineto(370,90); lineto(520,90);

  moveto(370,240); lineto(320,290); lineto(270,240);
  lineto(320,190); lineto(370,240);

  /* example */
  FloodFill(121,91,1,15);
  FloodFill(320,240,9,15);
  FloodFill(100,20,3,15);

  /* clean up */
  getch();
  end_gr();

  return 0;
}



Рисование линии

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Line drawing
//  (c) Johna Smith, 1996
//
//  Method description:
//    Determine k=dy/dx, dy=(y2-y1), dx=(x2-x1)
//    Line equation is: y(x)=y1+x*k so we need only to plot all
//    these points. This algorithm is very slow, because it use
//    floating point math (requires coprocessor for best productivity)
//  ! This program is NOT optimized for best performance !
//  To do so don't use putpixel function - change bytes in video memory directly.
//
//////////////////////////////////////////////////////////////////////////////

#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <math.h>

// this function initializes graphics mode
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void init_gr(void)
{
  /* request autodetection */
  int gdriver = DETECT, gmode, errorcode;

  /* initialize graphics mode */
  initgraph(&gdriver, &gmode, "");

  /* read result of initialization */
  errorcode = graphresult();

  if (errorcode != grOk)    /* an error occurred */
  {
     printf("Graphics error: %s\n", grapherrormsg(errorcode));
     printf("Press any key to halt:");
     getch();
     exit(1);               /* return with error code */
  }
}

// this function shuts graphics mode down
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void end_gr(void)
{
 closegraph();
}

// this function puts pixel on the screen in (x,y) position using color 'color'
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void PutPixel(int x, int y, int color)
{
 putpixel(x,y,color);
}

void Line(int x1,int y1,int x2, int y2, int color)
{
 int delta_x,delta_y,incx,incy;
 float k;

 // determine dx and dy
 delta_x=x2-x1;
 delta_y=y2-y1;

 // determine steps by x and y axes (it will be +1 if we move in forward
 // direction and -1 if we move in backward direction
 if (delta_x>0) incx=1;
 else if (delta_x==0) incx=0;
 else incx=-1;

 if (delta_y>0) incy=1;
 else if (delta_y==0) incy=0;
 else incy=-1;

 delta_x=abs(delta_x);
 delta_y=abs(delta_y);

 // select greatest from deltas and use it as a main axe
 if (delta_x>delta_y && delta_x!=0)
 {
    k=(float)delta_y/delta_x;
    for (int i=0;i<delta_x;i++) PutPixel(x1+incx*i,y1+incy*floor(k*i),color);
 }
 else
 {
    k=(float)delta_x/delta_y;
    for (int i=0;i<delta_y;i++) PutPixel(x1+incx*floor(k*i),y1+incy*i,color);
 }
}

int main(void)
{
 // initializing graphics mode
 init_gr();

 /* examples */
 Line(0, 0, 640, 480,15);
 Line(320, 0, 320, 480,10);
 Line(0, 240, 640, 240,11);
 Line(0, 480, 640, 0,12);
 Line(320, 11, 10, 5,13);
 Line(320, 11, 630, 5,13);

 /* clean up */
 getch();
 end_gr();

 return 0;
}



Рисование прямоугольника

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Rectangle drawing
//  (c) Johna Smith, 1996
//
//  Method description:
//  Draw four lines, using simplified line drawing method, cause we know
//  that only vertical and horizontal lines will be drawn.
//  ! This program is NOT optimized for best performance !
//  To do so don't use putpixel function - change bytes in video memory directly.
//
//////////////////////////////////////////////////////////////////////////////

#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <math.h>

// this function initializes graphics mode
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void init_gr(void)
{
  /* request autodetection */
  int gdriver = DETECT, gmode, errorcode;

  /* initialize graphics mode */
  initgraph(&gdriver, &gmode, "");

  /* read result of initialization */
  errorcode = graphresult();

  if (errorcode != grOk)    /* an error occurred */
  {
     printf("Graphics error: %s\n", grapherrormsg(errorcode));
     printf("Press any key to halt:");
     getch();
     exit(1);               /* return with error code */
  }
}

// this function shuts graphics mode down
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void end_gr(void)
{
 closegraph();
}

// this function puts pixel on the screen in (x,y) position using color 'color'
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void PutPixel(int x, int y, int color)
{
 putpixel(x,y,color);
}

void Line(int x1,int y1,int x2, int y2, int color)
{
 int delta_x,delta_y,incx,incy;

 // determine dx and dy
 delta_x=x2-x1;
 delta_y=y2-y1;

 // determine steps by x and y axes (it will be +1 if we move in forward
 // direction and -1 if we move in backward direction
 if (delta_x>0) incx=1;
 else if (delta_x==0) incx=0;
 else incx=-1;

 if (delta_y>0) incy=1;
 else if (delta_y==0) incy=0;
 else incy=-1;

 delta_x=abs(delta_x);
 delta_y=abs(delta_y);

 // select greatest from deltas and use it as a main axe
 if (delta_x!=0)
    for (int i=0;i<delta_x;i++) PutPixel(x1+incx*i,y1,color);
 else
    for (int i=0;i<delta_y;i++) PutPixel(x1,y1+incy*i,color);
}

// this function draws a rectangle
void Rectangle(int x1, int y1, int x2, int y2, int color)
{
 Line(x1,y1,x1,y2,color);
 Line(x1,y2,x2,y2,color);
 Line(x2,y2,x2,y1,color);
 Line(x2,y1,x1,y1,color);
}

int main(void)
{
 // initializing graphics mode
 init_gr();

 /* examples */
 Rectangle(0,0,639,479,10);
 Rectangle(100,200,300,400,11);
 Rectangle(600,100,20,11,12);

 /* clean up */
 getch();
 end_gr();

 return 0;
}



Фрактал (листья папоротника)
Код

//////////////////////////////////////////////////////////////////////////////
//
//  Leafs drawing
//  (c) Johna Smith, 1996
//
//  Method description:
//    We take a closed area, which will be main leaf. We want to generate
//  four fractal leafs from this one. To make it we need to scale, move and
//  rotate main leaf. These transformations described by the following
//  equations:
//          x'=ax+by+c, y'=dx+ey+f
//    So we need 6 coefficients for each leaf (24 coefficients at all).
//  These coefficients are calculated with special mathematical method
//  (here are already calculated coefficients)
//    To draw whole picture we need an iterational process:
//   1) Take any point within main leaf borders
//   2) Call function iterate for one of 4 leafs (its nuber we select
//      randomly but than the larger is leaf's area the higher is probability
//      that we call 'iterate' for this leaf
//   3) Then we take transformed point as (x,y) and repeat iterations
//
//  ! This program is NOT optimized for best performance !
//  To do so don't use putpixel function - change bytes in video memory directly.
//
//////////////////////////////////////////////////////////////////////////////

#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <graphics.h>
#include <conio.h>

// this function initializes graphics mode
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void init_gr(void)
{
   /* request autodetection */
   int gdriver = DETECT, gmode, errorcode;

   /* initialize graphics mode */
   initgraph(&gdriver, &gmode, "");

   /* read result of initialization */
   errorcode = graphresult();

   if (errorcode != grOk)    /* an error occurred */
   {
      printf("Graphics error: %s\n", grapherrormsg(errorcode));
      printf("Press any key to halt:");
      getch();
      exit(1);               /* return with error code */
   }
}

// this function shuts graphics mode down
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void end_gr(void)
{
 closegraph();
}

// this function puts pixel on the screen in (x,y) position using color 'color'
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void PutPixel(int x, int y, int color)
{
 putpixel(x,y,color);
}

#define N       200000L // number of points

float x=0, y=0; // iteration variables (are global)

//                       a     b     c    d    e    f        probability
float coeff[4][6] = {{ 0.00, 0.00, 0.00,0.16,0.00,0.00,},   // 01%
                    { 0.85, 0.04,-0.04,0.85,0.00,1.60,},   // 85%
                    { 0.05,-0.26, 0.23,0.22,0.00,1.60,},   // 07%
                    {-0.15, 0.30, 0.26,0.24,0.00,0.44,},}; // 07%

int colors[5]={10,11,2,3,2};

void iterate(char i,int c)
{
 float x1,y1;

 x1=x*coeff[i][0]+y*coeff[i][1]+coeff[i][4];
 y1=x*coeff[i][2]+y*coeff[i][3]+coeff[i][5];
 x=x1;
 y=y1;
 putpixel ((int)(y*64),240-(int)(x*48),c);
}

int main (void)
{
 int leaf,color;

 // initializing graphics mode
 init_gr();

 // drawing leafs
 for (long int i=0;i<N;i++)
 {
    color=colors[random(5)];  // random color
    leaf=random(1000);  // selecting leaf to draw
    if (leaf<=10) iterate(0,color);
    else if (leaf<=860) iterate(1,color);
    else if (leaf<=930) iterate(2,color);
    else iterate(3,color);
 }

 /* clean up */
 getch();
 end_gr();

 return 0;
}



Множество Мандельброта
Код

//////////////////////////////////////////////////////////////////////////////
//
//  Mandelbrot set drawing
//  (c) Johna Smith, 1996
//
//  Method description:
//    1) Assume z(0)=0
//    2) Organize two loops by X and Y axes
//    3) Determine constant C=X+iY
//    4) Using iterative formula z(i)=z(i-1)*z(i-1)+c calculate Z(DEPTH),
//       where DEPTH is max depth of iterations
//    5) If Z(DEPTH) is near Z(0) then point (X,Y) belongs to Mandelbrot set
//
//  ! This program is NOT optimized for best performance !
//  To do so don't use putpixel function - change bytes in video memory directly.
//
//////////////////////////////////////////////////////////////////////////////

#define DEPTH 100 // iterations depth

#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <math.h>

// this function initializes graphics mode
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void init_gr(void)
{
  /* request autodetection */
  int gdriver = DETECT, gmode, errorcode;

  /* initialize graphics mode */
  initgraph(&gdriver, &gmode, "");

  /* read result of initialization */
  errorcode = graphresult();

  if (errorcode != grOk)    /* an error occurred */
  {
     printf("Graphics error: %s\n", grapherrormsg(errorcode));
     printf("Press any key to halt:");
     getch();
     exit(1);               /* return with error code */
  }
}

// this function shuts graphics mode down
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void end_gr(void)
{
 closegraph();
}

// this function puts pixel on the screen in (x,y) position using color 'color'
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function

void PutPixel(int x, int y, int color)
{
 putpixel(x,y,color);
}

void Mandelbrot(void)
{
 float zi, zr, ci, cr, tmp;

 // assuming graphics mode 640x480 16 colors
 for(int i=-320;i<320;i++)  // for all pixels on the X axe
 {
    ci=((float)i)/320.0; // setting Im c = i/320
    for(int j=-380;j<160;j++)  // for all pixels on the Y axe
    {
       cr=((float)j)/240.0; // setting Re c = j/240
       zi=zr=0.0; // fixing z=0 we'll change c - it's Mandelbrot set
       for(int k=0;k<DEPTH;k++)
       {
  // z=z*z+c
  //(zr+i*zi)*(zr+i*zi)=(zr*zr-zi*zi)+i*(2*zr*zi)
  // zi=zr*zr-zi*zi+cr
  //
  tmp=zr*zr-zi*zi;
  zi=2*zr*zi+ci;
  zr=tmp+cr;
  if (zr*zr+zi*zi>1.0E16) break; // break if |z| is very big
}
if (k<DEPTH)
  PutPixel(i+320,j+380,k%3+1); // z was very big => it is external point
else PutPixel(i+320,j+380,11); // internal point
    }
    if(kbhit()) break;
 }
}

int main(void)
{
 // initializing graphics mode
 init_gr();

 /* example */
 Mandelbrot();

 /* clean up */
 getch();
 end_gr();

 return 0;
}

PM WWW ICQ   Вверх
podval
Дата 22.12.2004, 10:50 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Где я? Кто я?
****


Профиль
Группа: Экс. модератор
Сообщений: 3094
Регистрация: 25.3.2002
Где: СПб

Репутация: 18
Всего: 62



Специальные функции


arccos x (x - real)

Код

//////////////////////////////////////////////////////////////////////////////
//
//  arccos x function calculating.
//  (c) Johna Smith, 1996
//
//  Method description:
//    Calculating arccos x using the following formula:
//                                        2n+1
//              Pi       N  1*3*5..(2n-1)x
//   arccos x = - - x - SUM ------------------ , |x|<1
//              2       n=1 2*4*6..(2n)(2n+1)
//////////////////////////////////////////////////////////////////////////////

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

#define Pi      3.1415926536
#define N       30

double Arccos(double x)
{
 double arccos=x;
 double a=x;

 for (int i=1;i<N;i++)
 {
   a*=x*x*(2*i-1)*(2*i-1)/((2*i+1)*2*i);
   arccos+=a;
 }
 return Pi/2-arccos;
}

void main(void)
{
 printf("C++ arccos(0.5)=%g, this arccos(0.5)=%g.",acos(0.5),Arccos(0.5));
}



arccos z (z - complex)

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Calculactin function arccos z, where z is a complex value
//  (c) Johna Smith, 1996
//
//  Method description:
//       1            2    2     1            2    2
//    A= - sqrt( (x+1)  + y  ) + - sqrt( (x-1)  + y  )
//       2                       2
//
//       1            2    2     1            2    2
//    B= - sqrt( (x+1)  + y  ) - - sqrt( (x-1)  + y  )
//       2                       2
//                                       2
//    arccos z = acrcos B - i*ln(a+sqrt(a  -1))
//
//////////////////////////////////////////////////////////////////////////////

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

struct complex
{
 float re;
 float im;
};

void show_complex(complex c) // this functions displays complex value
{
 printf("%f%+fi",c.re,c.im);
}

complex Arccos(complex z)
{
 complex c;
 float A,B;

 A=sqrt((z.re+1)*(z.re+1)+z.im*z.im)/2 +
        sqrt((z.re-1)*(z.re-1)+z.im*z.im)/2;
 B=sqrt((z.re+1)*(z.re+1)+z.im*z.im)/2 -
        sqrt((z.re-1)*(z.re-1)+z.im*z.im)/2;

 c.re=acos(B);
 c.im=-log(A+sqrt(A*A-1));

 return c;
}

complex z={3,2};

void main(void)
{
 printf("Arccos(");
 show_complex(z);
 printf(") = ");
 show_complex(Arccos(z));
}



arch x

Код

//////////////////////////////////////////////////////////////////////////////
//
//  arcch x function calculating.
//  (c) Johna Smith, 1996
//
//  Method description:
//    Calculating arccos x using the following formula:
//
//                       N  1*3*5..(2n-1)       1
//   arcch x = ln(2x) - SUM --------------- * ------  , x>1
//                      n=1 2*4*6..(2n)(2n)   x^(2n)
//
//////////////////////////////////////////////////////////////////////////////

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

#define N       30

double Arch(double x)
{
 double arch=1/(2*x*2*x);
 double a=1/(2*x*2*x);

 for (int i=2;i<N;i++)
 {
   a *= (2*i-1)*(2*i-2)/(2*i*2*i*x*x);
   arch += a;
 }
 return log(2*x)-arch;
}

void main(void)
{
 printf("C++ arch(6.13229)=2.5, this arccos(6.13229)=%g.",Arch(6.13229));
}



arch z

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Calculactin function arccos z, where z is a complex value
//  (c) Johna Smith, 1996
//
//  Method description:
//       1            2    2     1            2    2
//    A= - sqrt( (x+1)  + y  ) + - sqrt( (x-1)  + y  )
//       2                       2
//
//       1            2    2     1            2    2
//    B= - sqrt( (x+1)  + y  ) - - sqrt( (x-1)  + y  )
//       2                       2
//                            2
//    arch z = +/- ln(a+sqrt(a  -1)) +/- i*acrcos B
//
//////////////////////////////////////////////////////////////////////////////

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

struct complex
{
 float re;
 float im;
};

void show_complex(complex c) // this functions displays complex value
{
 printf("%f%+fi",c.re,c.im);
}

complex Arch(complex z)
{
 complex c;
 float A,B;

 A=sqrt((z.re+1)*(z.re+1)+z.im*z.im)/2 +
        sqrt((z.re-1)*(z.re-1)+z.im*z.im)/2;
 B=sqrt((z.re+1)*(z.re+1)+z.im*z.im)/2 -
        sqrt((z.re-1)*(z.re-1)+z.im*z.im)/2;

 c.re=log(A+sqrt(A*A-1));
 c.im=-acos(B);

 return c;
}

complex z={3,2};

void main(void)
{
 complex c;

 printf("Arch(");
 show_complex(z);
 c=Arch(z);
 printf(") = +/- %f +/-i%f",c.re,c.im);
}



arcsin x

Код

//////////////////////////////////////////////////////////////////////////////
//
//  arcsin x function calculating.
//  (c) Johna Smith, 1996
//
//  Method description:
//    Calculating arcsin x using the following formula:
//                                      2n+1
//                     N  1*3*5..(2n-1)x
//    arcsin x  = x + SUM ------------------, |x|<1
//                    n=1 2*4*6..(2n)(2n+1)
//////////////////////////////////////////////////////////////////////////////

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

#define N       30

double Arcsin(double x)
{
 double arcsin=x;
 double a=x;

 for (int i=1;i<N;i++)
 {
   a *= x*x*(2*i-1)*(2*i-1)/((2*i+1)*2*i);
   arcsin += a;
 }
 return arcsin;
}

void main(void)
{
 printf("C++ arcsin(0.5)=%g, this arcsin(0.5)=%g.",asin(0.5),Arcsin(0.5));
}



arcsin z

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Calculactin function arcsin z, where z is a complex value
//  (c) Johna Smith, 1996
//
//  Method description:
//       1            2    2     1            2    2
//    A= - sqrt( (x+1)  + y  ) + - sqrt( (x-1)  + y  )
//       2                       2
//
//       1            2    2     1            2    2
//    B= - sqrt( (x+1)  + y  ) - - sqrt( (x-1)  + y  )
//       2                       2
//                                       2
//    arcsin z = acrsin B + i*ln(a+sqrt(a  -1))
//
//////////////////////////////////////////////////////////////////////////////

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

struct complex
{
 float re;
 float im;
};

void show_complex(complex c) // this functions displays complex value
{
 printf("%f%+fi",c.re,c.im);
}

complex Arcsin(complex z)
{
 complex c;
 float A,B;

 A=sqrt((z.re+1)*(z.re+1)+z.im*z.im)/2 +
 sqrt((z.re-1)*(z.re-1)+z.im*z.im)/2;
 B=sqrt((z.re+1)*(z.re+1)+z.im*z.im)/2 -
 sqrt((z.re-1)*(z.re-1)+z.im*z.im)/2;

 c.re=asin(B);
 c.im=log(A+sqrt(A*A-1));

 return c;
}

complex z={3,2};

void main(void)
{
 printf("Arcsin(");
 show_complex(z);
 printf(") = ");
 show_complex(Arcsin(z));
}



arctg x

Код

//////////////////////////////////////////////////////////////////////////////
//
//  arctg x function calculating.
//  (c) Johna Smith, 1996
//
//  Method description:
//    Calculating arctg x using the following formulas:
//                              2n+1
//                  N      n   x
//     arctg x  =  SUM (-1)  --------, |x|<1
//                 n=0         2n+1
//
//
//                  N      n+1       1
//     arctg x  =  SUM (-1)    --------------, |x|>1
//                 n=0         (2n+1)x^(2n+1)
//
//////////////////////////////////////////////////////////////////////////////

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

#define N       100
#define Pi      3.1415926536

double Arctg(double x)
{
 double arctg;
 double a;

 if (fabs(x)<1)
 {
   a=x;
   arctg=x;
   for (int i=1;i<N;i++)
   {
      a *= -x*x;
      arctg += a/(2*i+1);
   }
 }
 else
 {
   a=-1/x;
   arctg=-1/x;
   for (int i=1;i<N;i++)
   {
      a *= -1/(x*x);
      arctg += a/(2*i+1);
   }
   arctg += (x>0?Pi/2.0:-Pi/2.0);
 }

 return arctg;
}

void main(void)
{
 printf("C++ arctg(0.5)=%g, this arctg(0.5)=%g.",atan(0.5),Arctg(0.5));
}



arctg z

Код

//////////////////////////////////////////////////////////////////////////////
//
//  arctg z function calculating, where z is a complex value
//  (c) Johna Smith, 1996
//
//  Method description:
//
//                 1          2x          1    x^2+(y+1)^2
//     arctg z  =  - arctg(---------) + i - ln(-----------)
//                 2       1-x^2-y^2      4    x^2+(y-1)^2
//
//////////////////////////////////////////////////////////////////////////////

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

struct complex
{
 float re;
 float im;
};

void show_complex(complex c) // this functions displays complex value
{
 printf("%f%+fi",c.re,c.im);
}

complex Arctg(complex z)
{
 complex c;
 
 c.re=atan(2*z.re/(1-z.re*z.re-z.im*z.im))/2;
 c.im=log((z.re*z.re+(z.im+1)*(z.im+1))/(z.re*z.re+(z.im-1)*(z.im-1)))/4;

 return c;
}

complex z={0.3,0.2};

void main(void)
{
 printf("Arctg(");
 show_complex(z);
 printf(") = ");
 show_complex(Arctg(z));
}

PM WWW ICQ   Вверх
podval
Дата 22.12.2004, 11:09 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Где я? Кто я?
****


Профиль
Группа: Экс. модератор
Сообщений: 3094
Регистрация: 25.3.2002
Где: СПб

Репутация: 18
Всего: 62



arcsh x

Код

//////////////////////////////////////////////////////////////////////////////
//
//  arsh x function calculating.
//  (c) Johna Smith, 1996
//
//  Method description:
//    Calculating arccos x using the following formula:
//                                          2n+1
//                   N      n 1*3*5..(2n-1)x
//     arsh x = x + SUM (-1)  ------------------ , |x|<1
//                  n=1       2*4*6..(2n)(2n+1)
//////////////////////////////////////////////////////////////////////////////

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

#define N       30

double Arsh(double x)
{
 double arsh=x;
 double a=x;

 for (int i=1;i<N;i++)
 {
   a *= -x*x*(2*i-1)*(2*i-1)/((2*i+1)*2*i);
   arsh += a;
 }
 return arsh;
}

void main(void)
{
 printf("Exact arsh(0.5210953)=0.5, this arsh(0.5)=%g.",Arsh(0.5210953));
}



arcsh z

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Calculactin function arcsh z, where z is a complex value
//  (c) Johna Smith, 1996
//
//  Method description:
//       1            2    2     1            2    2
//    A= - sqrt( (x+1)  + y  ) + - sqrt( (x-1)  + y  )
//       2                       2
//
//       1            2    2     1            2    2
//    B= - sqrt( (x+1)  + y  ) - - sqrt( (x-1)  + y  )
//       2                       2
//                         2
//    arcsh z = ln(a+sqrt(a  -1)) - i*acrsin B
//
//////////////////////////////////////////////////////////////////////////////

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

struct complex
{
 float re;
 float im;
};

void show_complex(complex c) // this functions displays complex value
{
 printf("%f%+fi",c.re,c.im);
}

complex Arcsh(complex z)
{
 complex c;
 float A,B,swp;

 swp=z.im;    // calculating arsh(z) as -arcsin(iz)
 z.im=z.re;
 z.re=-swp;

 A=sqrt((z.re+1)*(z.re+1)+z.im*z.im)/2 +
        sqrt((z.re-1)*(z.re-1)+z.im*z.im)/2;
 B=sqrt((z.re+1)*(z.re+1)+z.im*z.im)/2 -
        sqrt((z.re-1)*(z.re-1)+z.im*z.im)/2;

 c.re=log(A+sqrt(A*A-1));
 c.im=-asin(B);

 return c;
}

complex z={3,2};

void main(void)
{
 printf("Arcsh(");
 show_complex(z);
 printf(") = ");
 show_complex(Arcsh(z));
}



arth x

Код

//////////////////////////////////////////////////////////////////////////////
//
//  arth x function calculating.
//  (c) Johna Smith, 1996
//
//  Method description:
//    Calculating arth x using the following formulas:
//                       2n+1
//                  N   x
//      arth x  =  SUM -------
//                 n=0  2n+1
//
//////////////////////////////////////////////////////////////////////////////

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

#define N       30

double Arth(double x)
{
 double arth=x;
 double a=x;

 for (int i=1;i<N;i++)
 {
   a *= x*x;
   arth += a/(2*i+1);
 }

 return arth;
}

void main(void)
{
 printf("Exact arth(0.4621171)=0.5, this arth(0.4621171)=%g.",Arth(0.4621171));
}



arth z

Код

//////////////////////////////////////////////////////////////////////////////
//
//  arctg z function calculating, where z is a complex value
//  (c) Johna Smith, 1996
//
//  Method description:
//
//                   1    x^2+(y+1)^2    1          2x
//     arctg z  =    - ln(-----------) -i- arctg(---------)
//                   4    x^2+(y-1)^2    2       1-x^2-y^2
//
//////////////////////////////////////////////////////////////////////////////

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

struct complex
{
 float re;
 float im;
};

void show_complex(complex c) // this functions displays complex value
{
 printf("%f%+fi",c.re,c.im);
}

complex Arth(complex z)
{
 complex c;
 float swp;

 swp=z.im;    // calculating arth(z) as -arctg(iz)
 z.im=z.re;
 z.re=-swp;

 c.re=log((z.re*z.re+(z.im+1)*(z.im+1))/(z.re*z.re+(z.im-1)*(z.im-1)))/4;
 c.im=-atan(2*z.re/(1-z.re*z.re-z.im*z.im))/2;

 return c;
}

complex z={0.3,0.2};

void main(void)
{
 printf("Arth(");
 show_complex(z);
 printf(") = ");
 show_complex(Arth(z));
}



Функция Бесселя

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Bessel functions calculating.
//  (c) Johna Smith, 1996
//
//  Method description:
//    Bessel functions are solutions of the followind eqation:
//         2                     2
//        d w     1 dw          v
//        ---- +  - -- + ( 1 - --- )w = 0
//          2     x dx           2
//        dx                    x
//
//    This program calculates Bessel functions for integer v as infinite sum
//
//////////////////////////////////////////////////////////////////////////////

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

// this function returns value of Jn(x)
double Jn(int n,double x)
{
 float nfact=1,ifact=1,nifact=1,sum=0,x2,element;
 int i;

 if (n>1) for (i=0;i<n;i++) nfact*=(i+1);  // n factorial
 x2=x*x/4;
 i=0;
 do
 {
   i++;
   ifact*=i;
   nifact*=(n+i);
   element=(i%2==0?1:-1)*pow(x2,i)/(ifact*nifact);
   sum+=element;
 } while (fabs(element)>1e-9);

 return pow(x/2,n)*(sum+1)/nfact;
}

// this function returns value of In(x)
double In(int n, double x)
{
 float nfact=1,ifact=1,nifact=1,sum=0,x2,element;
 int i;

 if (n>1) for (i=0;i<n;i++) nfact*=(i+1);  // n factorial
 x2=x*x/4;
 i=0;
 do
 {
   i++;
   ifact*=i;
   nifact*=(n+i);
   element=pow(x2,i)/(ifact*nifact);
   sum+=element;
 } while (fabs(element)>1e-9);

 return pow(x/2,n)*(sum+1)/nfact;
}

void main(void)
{
 // Examples
 printf("J0(0.5)=%f\n",Jn(0,0.5));
 printf("J30(20)=%f\n",Jn(30,20));
 printf("I0(2)=%f\n",In(0,2));
 printf("I1(2)=%f\n",In(1,2));
}



Гамма-функция

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Gamma function calculating.
//  (c) Johna Smith, 1996
//
//  Method description:
//             infinity  -t  x-1
//   Gamma(x)= Integral e   t    dt
//                0
//
//   This integral is approximated and calculated by Stirling's formula:
//                A
//             (A)    1/12A
//      Gamma= (-)  e       D sqrt(2 Pi A)
//             (e)
//
//   This algorithm is oriented for -10<x<=70
//
//////////////////////////////////////////////////////////////////////////////

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

#define E  2.7182818285
#define Pi 3.1415926536

// this function returns value of Gamma(x)
double Gamma(double x)
{
 double A,z,g,c,D;
 int b;

 A=x-1;
 z=A-64;
 if (z<0)
 {
   b=abs((int)(z-1));
   c=A;
   A+=b;
   D=1;
   for(int i=b;i>0;i--)
   {
      c++;
      D/=c;
   }
 } else D=1;
 g=pow(A/E,A)*exp(1/(12*A))*D*sqrt(2*Pi*A);

 return g;
}

void main(void)
{
 // Examples
 printf("Gamma(-1.5)=%f, exact value is 2.363271801\n",Gamma(-1.5));
 printf("Gamma(-0.5)=%f, exact value is -3.544907702\n",Gamma(-0.5));
 printf("Gamma(1.5)=%f, exact value is 0.886226926\n",Gamma(1.5));
 printf("Gamma(40)=%f, exact value is 2.039788208E+046\n",Gamma(40));
}



Бета-функция

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Beta function calculating.
//  (c) Johna Smith, 1996
//
//  Method description:
//                 1      x-1      w-1
//   Beta(x,w)= Integral t    (1-t)   dt
//                 0
//              Gamma(x) Gamma(w)
//   Beta(x,w)= -----------------
//                 Gamma(x+w)
//
//   This algorithm is oriented for -10 < x,w,x+w <= 70
//
//////////////////////////////////////////////////////////////////////////////

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

#define E       2.7182818285
#define Pi      3.1415926536

// this function returns value of Gamma(x)
double Gamma(double x)
{
 double A,z,g,c,D;
 int b;

 A=x-1;
 z=A-64;
 if (z<0)
 {
    b=abs((int)(z-1));
    c=A;
    A+=b;
    D=1;
    for(int i=b;i>0;i--)
    {
       c++;
       D/=c;
    }
 } else D=1;
 g=pow(A/E,A)*exp(1/(12*A))*D*sqrt(2*Pi*A);

 return g;
}

double Beta(double x, double w)
{
 return(Gamma(x)*Gamma(w)/Gamma(x+w));
}

void main(void)
{
 // Examples
 printf("Beta(1,2)=%f, exact value is 0.5\n",Beta(1,2));
}

PM WWW ICQ   Вверх
podval
Дата 22.12.2004, 11:21 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Где я? Кто я?
****


Профиль
Группа: Экс. модератор
Сообщений: 3094
Регистрация: 25.3.2002
Где: СПб

Репутация: 18
Всего: 62



ch x (x - real)

Код

//////////////////////////////////////////////////////////////////////////////
//
//  ch x function calculating.
//  (c) Johna Smith, 1996
//
//  Method description:
//    Calculating sh x using the following formulas:
//                      2n
//                  N  x
//        ch x  =  SUM ---
//                 n=0 2n!
//
//////////////////////////////////////////////////////////////////////////////

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

#define N       30

double Ch(double x)
{
 double ch=1;
 double a=1;

 for (int i=0;i<N;i++)
 {
   a *= x*x/((2*i+2)*(2*i+1));
   ch += a;
 }

 return ch;
}

void main(void)
{
 printf("Exact ch(0.5)=%g, this ch(0.5)=%g.",(exp(0.5)+exp(-0.5))/2,Ch(0.5));
}



ch z (z - complex)

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Calculactin function Ch(z), where z is a complex value
//  (c) Johna Smith, 1996
//
//  Method description:
//
//  ch z = ch x cos y + ish x sin y
//
//////////////////////////////////////////////////////////////////////////////

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

struct complex
{
 float re;
 float im;
};

#define N       30  // precision

double Ch(double x)
{
 double ch=1;
 double a=1;

 for (int i=0;i<N;i++)
 {
   a*=x*x/((2*i+2)*(2*i+1));
   ch+=a;
 }

 return ch;
}

double Sh(double x)
{
 double sh=x;
 double a=x;

 for (int i=1;i<N;i++)
 {
   a*=x*x/((2*i)*(2*i+1));
   sh+=a;
 }

 return sh;
}

void show_complex(complex c) // this functions displays complex value
{
 printf("%f%+fi",c.re,c.im);
}

complex complexCh(complex z)
{
 complex c;

 c.re=Ch(z.re)*cos(z.im);
 c.im=Sh(z.re)*sin(z.im);

 return c;
}

complex z={3,2};

void main(void)
{
 printf("Ch(");
 show_complex(z);
 printf(") = ");
 show_complex(complexCh(z));
}



cosec x (x - real)

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Cosecans function calculating.
//  (c) Johna Smith, 1996
//
//  Method description:
//    Calculating cosec x using the following formula:
//
//            1   1     7    3    31    5    127    7
//  cosec x = - + - x + --- x  + ----- x  + ------ x  + ...
//            x   6     360      15120      604800
//////////////////////////////////////////////////////////////////////////////

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

double Cosec(double x)
{
 double cosec=0;
 double coefficient[]={1, 1/6.0, 7/360.0, 31/15120.0, 127/604800.0};
 double a=1/x;

 for (int i=0;i<sizeof(coefficient)/sizeof(double);i++)
 {
   cosec+=a*coefficient[i];
   a*=x*x;
 }

 return cosec;
}

void main(void)
{
 printf("C++ cosec(0.5)=%g, this cosec(0.5)=%g.",1/sin(0.5),Cosec(0.5));
}



cos x

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Cosine function calculating.
//  (c) Johna Smith, 1996
//
//  Method description:
//    Calculating cos x using the following formula:
//                  2     4     6     8
//                 x     x     x     x
//    cos x = 1 - --- + --- - --- + --- - ...
//                 2!    4!    6!    8!
//////////////////////////////////////////////////////////////////////////////

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

#define N       300

double Cos(double x)
{
 double cos=0;
 double a=1;

 for (int i=1;i<N;i++)
 {
   cos+=a;
   a=-a*x*x/((2*i-1)*2*i);
 }
 return cos;
}

void main(void)
{
 printf("C++ Cos(0.5)=%g, this Cos(0.5)=%g.",cos(0.5),Cos(0.5));
}



cos z (z - complex)

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Calculactin function cos(z), where z is a complex value
//  (c) Johna Smith, 1996
//
//  Method description:
//
//  cos z = cos x ch y + isin x sh y
//
//////////////////////////////////////////////////////////////////////////////

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

struct complex
{
 float re;
 float im;
};

#define N       30  // precision

double Ch(double x)
{
 double ch=1;
 double a=1;

 for (int i=0;i<N;i++)
 {
   a*=x*x/((2*i+2)*(2*i+1));
   ch+=a;
 }

 return ch;
}

double Sh(double x)
{
 double sh=x;
 double a=x;

 for (int i=1;i<N;i++)
 {
   a*=x*x/((2*i)*(2*i+1));
   sh+=a;
 }

 return sh;
}

void show_complex(complex c) // this functions displays complex value
{
 printf("%f%+fi",c.re,c.im);
}

complex Cos(complex z)
{
 complex c;

 c.re=cos(z.re)*Ch(z.im);
 c.im=sin(z.re)*Sh(z.im);

 return c;
}

complex z={3,2};

void main(void)
{
 printf("Cos(");
 show_complex(z);
 printf(") = ");
 show_complex(Cos(z));
}



ctg x

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Cotangent function calculating.
//  (c) Johna Smith, 1996
//
//  Method description:
//    Calculating ctg x using the following formula:
//
//            1   1     1   3    2   5    1    7
//    ctg x = - - - x - -- x  - --- x  - ---- x  - ...
//            x   3     45      945      4725
//////////////////////////////////////////////////////////////////////////////

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

double Ctg(double x)
{
 double ctg=0;
 double coefficient[]={1, -1/3.0, -1/45.0, -2/945.0, -1/4725.0};
 double a=1/x;

 for (int i=0;i<sizeof(coefficient)/sizeof(double);i++)
 {
   ctg += a*coefficient[i];
   a *= x*x;
 }

 return ctg;
}

void main(void)
{
 printf("C++ ctg(0.5)=%g, this ctg(0.5)=%g.",1/tan(0.5),Ctg(0.5));
}

PM WWW ICQ   Вверх
podval
Дата 22.12.2004, 20:55 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Где я? Кто я?
****


Профиль
Группа: Экс. модератор
Сообщений: 3094
Регистрация: 25.3.2002
Где: СПб

Репутация: 18
Всего: 62



e^x (x - real)

Код

//////////////////////////////////////////////////////////////////////////////
//
//  e^x function calculating.
//  (c) Johna Smith, 1996
//
//  Method description:
//    Calculating e^x using the following formula:
//                   2    3
//     x       x    x    x  
//    e  = 1 + -- + -- + -- + ...
//             1!   2!   3!
//////////////////////////////////////////////////////////////////////////////

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

#define N       300

double Exp(double x)
{
 double exp=0;
 double a=1;

 for (int i=1;i<N;i++)
 {
   exp+=a;
   a*=x/i;
 }
 return exp;
}

void main(void)
{
 printf("C++ exp(10)=%g, this exp(10)=%g.",exp(10),exp(10));
}



e^z (z - complex)

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Calculactin function e^z, where z is a complex value
//  (c) Johna Smith, 1996
//
//  Method description:
//
//  e^z = e^x cos y + i e^x sin y
//
//////////////////////////////////////////////////////////////////////////////

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

struct complex
{
 float re;
 float im;
};

void show_complex(complex c) // this functions displays complex value
{
 printf("%f%+fi",c.re,c.im);
}

complex Exp(complex z)
{
 complex c;

 c.re=exp(z.re)*cos(z.im);
 c.im=exp(z.re)*sin(z.im);

 return c;
}

complex z={3,2};

void main(void)
{
 printf("Exp(");
 show_complex(z);
 printf(") = ");
 show_complex(Exp(z));
}



tg x (x - real)

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Tangent function calculating.
//  (c) Johna Smith, 1996
//
//  Method description:
//    Calculating tg x using the following formula:
//
//                1  3   2   5   17   7   62    9
//     tg x = x + - x  + -- x  + --- x  + ---- x  + ...
//                3      15      315      2835
//////////////////////////////////////////////////////////////////////////////

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

double Tg(double x)
{
 double tg=0;
 double coefficient[]={1,1/3.0,2/15.0,17/315.0,62/2835.0};
 double a=x;

 for (int i=0;i<sizeof(coefficient)/sizeof(double);i++)
 {
   tg+=a*coefficient[i];
   a*=x*x;
 }

 return tg;
}

void main(void)
{
 printf("C++ Tg(0.5)=%g, this Tg(0.5)=%g.",tan(0.5),Tg(0.5));
}



tg z (z - complex)

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Calculactin function tg(z), where z is a complex value
//  (c) Johna Smith, 1996
//
//  Method description:
//
//             sin(2x)             sh(2y)
//  tg z = --------------- + i --------------
//         cos(2x)+ch(2*y)     cos(2x)+ch(2y)
//////////////////////////////////////////////////////////////////////////////

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

struct complex
{
 float re;
 float im;
};

#define N       30  // precision

double Ch(double x)
{
 double ch=1;
 double a=1;

 for (int i=0;i<N;i++)
 {
   a*=x*x/((2*i+2)*(2*i+1));
   ch+=a;
 }

 return ch;
}

double Sh(double x)
{
 double sh=x;
 double a=x;

 for (int i=1;i<N;i++)
 {
   a*=x*x/((2*i)*(2*i+1));
   sh+=a;
 }

 return sh;
}

void show_complex(complex c) // this functions displays complex value
{
 printf("%f%+fi",c.re,c.im);
}

complex Tg(complex z)
{
 complex c;

 c.re=sin(2*z.re)/(cos(2*z.re)+Ch(2*z.im));
 c.im=Sh(2*z.im)/(cos(2*z.re)+Ch(2*z.im));

 return c;
}

complex z={3,2};

void main(void)
{
 printf("Tg(");
 show_complex(z);
 printf(") = ");
 show_complex(Tg(z));
}



th x (x - real)

Код

//////////////////////////////////////////////////////////////////////////////
//
//  th x function calculating.
//  (c) Johna Smith, 1996
//
//  Method description:
//    Calculating th x using the following formula:
//
//                1  3   2   5   17   7    62   9                Ї
//    sec x = x - - x  + -- x  - --- x  + ---- x  - ... ,  |x| < -
//                3      15      315      2835                   2
//////////////////////////////////////////////////////////////////////////////

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

double Th(double x)
{
 double th=0;
 double coefficient[]={1, -1/3.0, 2/15.0, -17/315.0, 62/2835.0};
 double a=x;

 for (int i=0;i<sizeof(coefficient)/sizeof(double);i++)
 {
   th += a*coefficient[i];
   a *= x*x;
 }

 return th;
}

void main(void)
{
 printf("Exact th(0.5)=%g, this th(0.5)=%g.",
        (exp(0.5)-exp(-0.5))/(exp(0.5)+exp(-0.5)),Th(0.5));
}



th z (z - complex)

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Calculactin function th(z), where z is a complex value
//  (c) Johna Smith, 1996
//
//  Method description:
//
//              sh(2x)             sin(2y)
//  th z = --------------- + i --------------
//         ch(2x)+cos(2*y)     ch(2x)+cos(2y)
//////////////////////////////////////////////////////////////////////////////

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

struct complex
{
 float re;
 float im;
};

#define N       30  // precision

double Ch(double x)
{
 double ch=1;
 double a=1;

 for (int i=0;i<N;i++)
 {
   a*=x*x/((2*i+2)*(2*i+1));
   ch+=a;
 }

 return ch;
}

double Sh(double x)
{
 double sh=x;
 double a=x;

 for (int i=1;i<N;i++)
 {
   a*=x*x/((2*i)*(2*i+1));
   sh+=a;
 }

 return sh;
}

void show_complex(complex c) // this functions displays complex value
{
 printf("%f%+fi",c.re,c.im);
}

complex complexTh(complex z)
{
 complex c;

 c.re=Sh(2*z.re)/(Ch(2*z.re)+cos(2*z.im));
 c.im=sin(2*z.im)/(Ch(2*z.re)+cos(2*z.im));

 return c;
}

complex z={3,2};

void main(void)
{
 printf("Th(");
 show_complex(z);
 printf(") = ");
 show_complex(complexTh(z));
}



sin x (x- real)

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Sine function calculating.
//  (c) Johna Smith, 1996
//
//  Method description:
//    Calculating sin x using the following formula:
//                  3     5     7     9
//                 x     x     x     x
//    sin x = x - --- + --- - --- + --- - ...
//                 3!    5!    7!    9!
//////////////////////////////////////////////////////////////////////////////

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

#define N       300

double Sin(double x)
{
 double sin=0;
 double a=x;

 for (int i=1;i<N;i++)
 {
   sin+=a;
   a=-a*x*x/((2*i+1)*2*i);
 }
 return sin;
}

void main(void)
{
 printf("C++ Sin(0.5)=%g, this Sin(0.5)=%g.",sin(0.5),Sin(0.5));
}



sin z (z - complex)

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Calculactin function sin(z), where z is a complex value
//  (c) Johna Smith, 1996
//
//  Method description:
//
//  sin z = sin x ch y + icos x sh y
//
//////////////////////////////////////////////////////////////////////////////

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

struct complex
{
 float re;
 float im;
};

#define N       30  // precision

double Ch(double x)
{
 double ch=1;
 double a=1;

 for (int i=0;i<N;i++)
 {
   a*=x*x/((2*i+2)*(2*i+1));
   ch+=a;
 }

 return ch;
}

double Sh(double x)
{
 double sh=x;
 double a=x;

 for (int i=1;i<N;i++)
 {
   a*=x*x/((2*i)*(2*i+1));
   sh+=a;
 }

 return sh;
}

void show_complex(complex c) // this functions displays complex value
{
 printf("%f%+fi",c.re,c.im);
}

complex Sin(complex z)
{
 complex c;

 c.re=sin(z.re)*Ch(z.im);
 c.im=cos(z.re)*Sh(z.im);

 return c;
}

complex z={3,2};

void main(void)
{
 printf("Sin(");
 show_complex(z);
 printf(") = ");
 show_complex(Sin(z));
}



sec x (x - real)

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Secans function calculating.
//  (c) Johna Smith, 1996
//
//  Method description:
//    Calculating sec x using the following formula:
//
//                1  2   5   4   61   6   277   8
//    sec x = 1 + - x  + -- x  + --- x  + ---- x  + ...
//                2      24      720      8064
//////////////////////////////////////////////////////////////////////////////

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

double Sec(double x)
{
 double sec=0;
 double coefficient[]={1, 1/2.0, 5/24.0, 61/720.0, 277/8064.0};
 double a=1;

 for (int i=0;i<sizeof(coefficient)/sizeof(double);i++)
 {
   sec+=a*coefficient[i];
   a*=x*x;
 }

 return sec;
}

void main(void)
{
 printf("C++ Sec(0.5)=%g, this Sec(0.5)=%g.",1/cos(0.5),Sec(0.5));
}



sh x (x - real)

Код

//////////////////////////////////////////////////////////////////////////////
//
//  sh x function calculating.
//  (c) Johna Smith, 1996
//
//  Method description:
//    Calculating sh x using the following formulas:
//                       2n-1
//                  N   x
//        sh x  =  SUM -------
//                 n=1 (2n-1)!
//
//////////////////////////////////////////////////////////////////////////////

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

#define N       30

double Sh(double x)
{
 double sh=x;
 double a=x;

 for (int i=1;i<N;i++)
 {
   a*=x*x/((2*i)*(2*i+1));
   sh+=a;
 }

 return sh;
}

void main(void)
{
 printf("Exact sh(0.5)=%g, this sh(0.5)=%g.",(exp(0.5)-exp(-0.5))/2,Sh(0.5));
}



sh z (z - complex)

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Calculactin function Sh(z), where z is a complex value
//  (c) Johna Smith, 1996
//
//  Method description:
//
//  sh z = sh x cos y + ich x sin y
//
//////////////////////////////////////////////////////////////////////////////

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

struct complex
{
 float re;
 float im;
};

#define N       30  // precision

double Ch(double x)
{
 double ch=1;
 double a=1;

 for (int i=0;i<N;i++)
 {
   a*=x*x/((2*i+2)*(2*i+1));
   ch+=a;
 }

 return ch;
}

double Sh(double x)
{
 double sh=x;
 double a=x;

 for (int i=1;i<N;i++)
 {
   a*=x*x/((2*i)*(2*i+1));
   sh+=a;
 }

 return sh;
}

void show_complex(complex c) // this functions displays complex value
{
 printf("%f%+fi",c.re,c.im);
}

complex complexSh(complex z)
{
 complex c;

 c.re=Sh(z.re)*cos(z.im);
 c.im=Ch(z.re)*sin(z.im);

 return c;
}

complex z={3,2};

void main(void)
{
 printf("Sh(");
 show_complex(z);
 printf(") = ");
 show_complex(complexSh(z));
}

PM WWW ICQ   Вверх
podval
Дата 22.12.2004, 21:05 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Где я? Кто я?
****


Профиль
Группа: Экс. модератор
Сообщений: 3094
Регистрация: 25.3.2002
Где: СПб

Репутация: 18
Всего: 62



Факториал (формула Стирлинга)

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Factorial calculation (Stirling solution)
//  (c) Johna Smith, 1996
//
//  Method description:
//   We just use Stirling method, improving it by using fast method
//  of calculating n^n.
//   !! Warning! this formula gives best results ONLY if n>>10
//
//////////////////////////////////////////////////////////////////////////////

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

#define Pi 3.1415926536

long double factorial (long int n)
{
 long double factorial,b=1,tmp;
 long int k;

 factorial=sqrt(2*Pi*n)*exp(-n+(1-1/(30*n))/(12*n));

 // quick powering n^n
 tmp=n;
 k=n;
 while (k!=0)
 {
   if (k%2!=0) b*=tmp;
   k/=2;
   tmp*=tmp;
 }
 factorial*=b;

 return factorial;
}

void main(void)
{
 printf("5! = %Lf\n35! = %Lf\n100! = %Lf\n",factorial(5L),
                       factorial(35L),factorial(100L));
}



sqrt(z), where z is a complex value

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Calculactin function sqrt(z), where z is a complex value
//  (c) Johna Smith, 1996
//
//  Method description:
//
//  sqrt(z) = +/- sqrt((x+sqrt(x^2+y^2))/2) +/- i*sqrt(-x+sqrt(x^2+y^2))/2)
//
//////////////////////////////////////////////////////////////////////////////

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

struct complex
{
 float re;
 float im;
};

void show_complex(complex c) // this functions displays complex value
{
 printf("%f%+fi",c.re,c.im);
}

complex Sqrt(complex z)
{
 complex c;

 c.re=sqrt((z.re+sqrt(z.re*z.re+z.im*z.im))/2);
 c.im=sqrt((-z.re+sqrt(z.re*z.re+z.im*z.im))/2);

 return c;
}

complex z={3,2};

void main(void)
{
 printf("Sqrt(");
 show_complex(z);
 z=Sqrt(z);
 printf(") = +/- %f +/- i*%f",z.re,z.im);
}



ln x (x - real)

Код

//////////////////////////////////////////////////////////////////////////////
//
//  ln x function calculating.
//  (c) Johna Smith, 1996
//
//  Method description:
//    Calculating ln x using the following formula:
//
//               N     (x-1)^(2n+1)
//    ln x  = 2 SUM ------------------
//              n=0 (2n+1)(x+1)^(2n+1)
//////////////////////////////////////////////////////////////////////////////

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

#define N       300

double Ln(double x)
{
 double ln=0;
 double a=(x+1)/(x-1);

 for (int i=0;i<N;i++)
 {
   a*=(x-1)*(x-1)/((x+1)*(x+1));
   ln+=a/(2*i+1);
 }
 return 2*ln;
}

void main(void)
{
 printf("C++ ln(10)=%g, this ln(10)=%g.",log(10),Ln(10));
}



ln z (z - complex)

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Calculactin function ln z, where z is a complex value
//  (c) Johna Smith, 1996
//
//  Method description:
//         1   2   2             y
//  ln z = - (x + y ) + i*(arctg - +2kЇ), k=0, +/-1, +/-2, ...
//         2                     x
//////////////////////////////////////////////////////////////////////////////

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

struct complex
{
 float re;
 float im;
};

void show_complex(complex c) // this functions displays complex value
{
 printf("%f%+fi",c.re,c.im);
}

complex Ln(complex z)
{
 complex c;

 c.re=log(z.re*z.re+z.im*z.im)/2;
 c.im=atan(z.im/z.re); // you can add 2kЇ here (we assume that k=0)

 return c;
}

complex z={3,2};

void main(void)
{
 printf("Ln(");
 show_complex(z);
 printf(") = ");
 show_complex(Ln(z));
}

PM WWW ICQ   Вверх
podval
Дата 22.12.2004, 21:21 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Где я? Кто я?
****


Профиль
Группа: Экс. модератор
Сообщений: 3094
Регистрация: 25.3.2002
Где: СПб

Репутация: 18
Всего: 62



Динамические структуры данных


Bidirectional cycled list

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Dynamic structures (bidirectional cycled list)
//  (c) Johna Smith, 1996
//
//  Method description:
// .................
// -> * -> * -> * ->
// <- * <- * <- * <-
// .  A    B    C  .
// .................
//////////////////////////////////////////////////////////////////////////////

#include <stdio.h>
#include <alloc.h>

struct item
{
 int element;
 item *prev;
 item *next;
};

item *list; // base element of the list

// this function removes element pointed by i from list

void Remove(item* i)
{
 i->next->prev=i->prev;
 i->prev->next=i->next;
 free(i);
}

// this function inserts element after
// element pointed by i
void Insert(item *i, int element)
{
 item *tmp;

 // creating new item
 tmp=(item*)malloc(sizeof(item));
 tmp->element=element;
 tmp->next=i->next;
 tmp->prev=i->next->prev;
 // correcting nearest elements pointers
 i->next->prev=tmp;
 i->next=tmp;
}

// this function searches element in the list
item* Search(int element)
{
 item *p,*q,*result=NULL;
 char found=0;

 p=list;
 q=list->next;
 
 while (p!=q && found==0)
 {
   if (q->element==element)
   {
     found=1;
     result=q;
   }
   q=q->next;
 }

 return result;
}

// this function prints the list
void printlist(void)
{
 item *p;

 p=list->next;
 while (p!=list)
 {
   printf("%d ",p->element);
   p=p->next;
 }
}

void main(void)
{
 // creating first element of the list
 list=(item*)malloc(sizeof(item));
 list->element=0;
 list->next=list;
 list->prev=list;

 printf("Adding elements 1,2,4 & 5\n");
 Insert(list,5);
 Insert(list,4);
 Insert(list,2);
 Insert(list,1);
 printlist();
 printf("\nSearching element 2\n");
 item *tmp=Search(2);
 printf("Inserting element 3 after it\n");
 Insert(tmp,3);
 printlist();
 printf("\nDeleting element 1\n");
 Remove(list->next);
 printlist();

 // destroying list
 while (list->next!=list) Remove(list->next);
 free(list);
}



Binary tree

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Dynamic structures (binary tree)
//  (c) Johna Smith, 1996
//
//  Method description:
//               *
//            /     \
//           *       *
//         /   \   /   \
//        *     * *     *
//
//   From current element X left element is less than X and right element
// is greater than X. All elements in the must be different.
//
//////////////////////////////////////////////////////////////////////////////

#include <stdio.h>
#include <alloc.h>
#include <conio.h>
#include <math.h>

struct item
{
 int element;
 item *left;
 item *right;
};

item *tree; // base element of the list

// this function searches element in the tree and returns 0 if element wasn't
// found and 1 - if element was found, result is address of element
char Search(int element, item** result)
{
 item *p,*q;
 char found=0;

 p=tree;
 if (tree!=NULL)
 do
 {
   q=p;
   if (p->element==element) found=1;
   else
   {
     q=p;
     if (element<p->element) p=p->left;
     else p=p->right;
   }
 }
 while (!found && p!=NULL);
 *result=q;

 return found;
}

// this function adds an element to the tree
void Add(int element)
{
 item *r,*s;

 if (Search(element,&r)==0)
 {
   s=(item*)malloc(sizeof(item));
   s->element=element;
   s->left=NULL;
   s->right=NULL;
   if (tree==NULL) tree=s; // if tree is empty make s=top of the tree
   else
   {
     if (element<r->element) r->left=s;
     else r->right=s;
   }
 }
}

// this is auxulary function for Remove procedure
void Del(item **r, item **q)
{
 item *tmp;

 if ((*r)->right==NULL)
 {
   (*q)->element=(*r)->element;
   *q=*r;
   *r=(*r)->left;
 }
 else Del(&((*r)->right),q);
}

// this function removes element with value 'element' from the tree
void Remove(int element, item **d)
{
 item *q;

 if (*d==NULL)
 printf("There is not element %d in the tree.\n",element);
 else
 if (element<(*d)->element) Remove(element, &((*d)->left)); else
 if (element>(*d)->element) Remove(element, &((*d)->right)); else
 {
   // element found
   q=*d;
   if (q->right==NULL) *d=q->left; else
   if (q->left==NULL) *d=q->right; else
   Del(&(q->left),&q);
   free(q);
 }
}

// this function prints the tree
void printtree(item *t, int offset=40, int depth=2)
{
 gotoxy(offset,depth);
 cprintf("%d",t->element);
 if (t->left!=NULL) printtree(t->left,offset-pow(2,6-depth),depth+1);
 if (t->right!=NULL) printtree(t->right,offset+pow(2,6-depth),depth+1);
}

void main(void)
{
 item *tmp;

 // creating tree
 Add(100);
 Add(20);
 Add(120);
 Add(15);
 Add(50);
 Add(130);
 Add(30);
 Add(55);
 Add(28);
 Add(35);
 Add(60);
 Add(33);

 // printing tree
 clrscr();
 printf("Press a key to delete element 50...\n");
 printtree(tree);
 getch();
 clrscr();
 Remove(50,&tree);
 printtree(tree);
 gotoxy(1,20);
 // searching
 cprintf("Element 20 is%s found",(Search(20,&tmp)?"":"n't"));
 printf("\nElement 25 is%s found\n",(Search(25,&tmp)?"":"n't"));
 // removing all elements
 Remove(100,&tree);
 Remove(20,&tree);
 Remove(120,&tree);
 Remove(15,&tree);
 Remove(35,&tree);
 Remove(130,&tree);
 Remove(30,&tree);
 Remove(55,&tree);
 Remove(28,&tree);
 Remove(33,&tree);
 Remove(60,&tree);
}



Stack

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Dynamic structures (stack)
//  (c) Johna Smith, 1996
//
//  Method description:
//    Stack is the queue with LIFO structure (Last In First Out)
//    There is only one accesible element in the stack - its top
//    Two operations defined for stack - pushing element to stack
//    and popping element feom stack
//
//////////////////////////////////////////////////////////////////////////////

#include <stdio.h>
#include <alloc.h>

struct item
{
 int element;
 item *next;
};

item *stack=NULL; // base element of the stack

// this function pushes an to stack
void Push(int element)
{
 item *q;
 
 q=(item*)malloc(sizeof(item));
 q->element=element;
 q->next=stack;
 stack=q;
}

// this function pops an element from stack
int Pop(void)
{
 int result;
 item *q;
 
 if (stack==NULL)
   printf("!POP error: stack is EMPTY");
 else
 {
   result=stack->element;
   q=stack;
   stack=stack->next;
   free(q);
 }
 return result;
}

// this function prints the stack
void printstack(void)
{
 item *p;

 p=stack;
 while (p!=NULL)
 {
   printf("%d ",p->element);
   p=p->next;
 }
}

void main(void)
{
 printstack();
 printf("Pushing elements 1,2,3\n");
 Push(1);
 Push(2);
 Push(3);
 printstack();
 printf("\nPopping 2 elements\n");
 printf("%d ",Pop());
 printf("%d\n",Pop());
 printstack();

 // destroying stack
 while (stack!=NULL) Pop();
}



List

Код

//////////////////////////////////////////////////////////////////////////////
//
//  Dynamic structures (list)
//  (c) Johna Smith, 1996
//
//  Method description:
//    * -> * -> * -> nil
//    A    B    C
//
//////////////////////////////////////////////////////////////////////////////

#include <stdio.h>
#include <alloc.h>

struct item
{
 int element;
 item *next;
};

item *list; // base element of the list
item *p; // current pointer

// this function adds an element to the end of list
void Add(int element)
{
 p->next=(item*)malloc(sizeof(item));
 p=p->next;
 p->element=element;
 p->next=NULL;
}

// this function removes element from list
// after element pointed by i
void Remove(item* i)
{
 item *tmp;

 if (i->next!=NULL)
 {
   tmp=i->next;
   i->next=(i->next)->next;
   free(tmp);
 }
}

// this function inserts element after
// element pointed by i
void Insert(item *i, int element)
{
 item *tmp;

 tmp=(item*)malloc(sizeof(item));
 tmp->element=element;
 tmp->next=i->next;
 i->next=tmp;
}

// this function searches element in the list
item* Search(int element)
{
 item *i,*result=NULL;
 char found=0;

 i=list->next;
 while (i!=NULL && found==0)
 {
   if (i->element==element)
   {
     found=1;
     result=i;
   }
   i=i->next;
 }

 return result;
}

// this function prints the list
void printlist(void)
{
 item *p;

 p=list->next;
 while (p!=NULL)
 {
   printf("%d ",p->element);
   p=p->next;
 }
}

void main(void)
{
 // creating first element of the list
 list=(item*)malloc(sizeof(item));
 list->element=0;
 list->next=NULL;
 p=list;

 printf("Adding elements 1,2 & 4\n");
 Add(1);
 Add(2);
 Add(4);
 printlist();
 printf("\nSearching element 2\n");
 item *tmp=Search(2);
 printf("Inserting element 3 after it\n");
 Insert(tmp,3);
 printlist();
 printf("\nDeleting element 1\n");
 Remove(list);
 printlist();

 // destroying list
 while (list->next!=NULL) Remove(list);
 free(list);
}

PM WWW ICQ   Вверх
Страницы: (3) Все [1] 2 3 
Закрытая темаСоздание новой темы Создание опроса
Правила форума "Алгоритмы"

maxim1000

Форум "Алгоритмы" предназначен для обсуждения вопросов, связанных только с алгоритмами и структурами данных, без привязки к конкретному языку программирования и/или программному продукту.


Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, maxim1000.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Алгоритмы | Следующая тема »


 




[ Время генерации скрипта: 0.3249 ]   [ Использовано запросов: 21 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.