| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 5407 人关注过本帖
标题:大家来看看这个遗传算法程序C
只看楼主 加入收藏
hujia358
Rank: 1
等 级:新手上路
帖 子:3
专家分:0
注 册:2008-6-12
收藏
 问题点数:0 回复次数:7 
大家来看看这个遗传算法程序C
#include <stdio.h>
#include<graphics.h>
#include <math.h>
#include "graph.c"
/* 全局变量 */
struct individual                       /* 个体*/
{
    unsigned *chrom;                    /* 染色体 */
    double   fitness;                   /* 个体适应度*/
    double   varible;                   /* 个体对应的变量值*/   
    int      xsite;                     /* 交叉位置 */
    int      parent[2];                 /* 父个体  */
    int      *utility;                  /* 特定数据指针变量 */
};
struct bestever                         /* 最佳个体*/
{
    unsigned *chrom;                    /* 最佳个体染色体*/
    double   fitness;                   /* 最佳个体适应度 */
    double   varible;                   /* 最佳个体对应的变量值 */
    int      generation;                /* 最佳个体生成代 */
};
 struct individual *oldpop;             /* 当前代种群 */
 struct individual *newpop;             /* 新一代种群 */
 struct bestever bestfit;               /* 最佳个体 */
 double sumfitness;                     /* 种群中个体适应度累计 */
 double max;                            /* 种群中个体最大适应度 */
 double avg;                            /* 种群中个体平均适应度 */
 double min;                            /* 种群中个体最小适应度 */
 float  pcross;                         /* 交叉概率 */
 float  pmutation;                      /* 变异概率 */
 int    popsize;                        /* 种群大小  */
 int    lchrom;                         /* 染色体长度*/
 int    chromsize;                      /* 存储一染色体所需字节数 */
 int    gen;                            /* 当前世代数 */
 int    maxgen;                         /* 最大世代数   */
 int    run;                            /* 当前运行次数 */
 int    maxruns;                        /* 总运行次数   */
 int    printstrings;                   /* 输出染色体编码的判断,0 -- 不输出, 1 -- 输出 */
 int    nmutation;                      /* 当前代变异发生次数 */
 int    ncross;                         /* 当前代交叉发生次数 */
/* 随机数发生器使用的静态变量 */
static double oldrand[55];
static int jrand;
static double rndx2;
static int rndcalcflag;
/* 输出文件指针 */
FILE *outfp ;
/* 函数定义 */
void advance_random();
int flip(float);rnd(int, int);
void randomize();
double randomnormaldeviate();
float randomperc(),rndreal(float,float);
void warmup_random(float);
void initialize(),initdata(),initpop();
void initreport(),generation(),initmalloc();
void freeall(),nomemory(char *),report();
void writepop(),writechrom(unsigned *);
void preselect();
void statistics(struct individual *);
void title(),repchar (FILE *,char *,int);
void skip(FILE *,int);
int select();
void objfunc(struct individual *);
int crossover (unsigned *, unsigned *, unsigned *, unsigned *);
void mutation(unsigned *);

void initialize()      /* 遗传算法初始化 */
{
    /* 键盘输入遗传算法参数 */
    initdata();
    /* 确定染色体的字节长度 */
    chromsize = (lchrom/(8*sizeof(unsigned)));
    if(lchrom%(8*sizeof(unsigned))) chromsize++;
    /*分配给全局数据结构空间 */
    initmalloc();
    /* 初始化随机数发生器 */
    randomize();
    /* 初始化全局计数变量和一些数值*/
    nmutation = 0;
    ncross = 0;
    bestfit.fitness = 0.0;
    bestfit.generation = 0;
    /* 初始化种群,并统计计算结果 */
    initpop();
    statistics(oldpop);
    initreport();
}
void initdata()           /* 遗传算法参数输入 */
{
   char  answer[2];
    setcolor(9);
    disp_hz16("种群大小(20-100):",100,150,20);
    gscanf(320,150,9,15,4,"%d", &popsize);
    if((popsize%2) != 0)
      {
 fprintf(outfp, "种群大小已设置为偶数\n");
 popsize++;
      };
   setcolor(9);
   disp_hz16("染色体长度(8-40):",100,180,20);
   gscanf(320,180,9,15,4,"%d", &lchrom);
   setcolor(9);
   disp_hz16("是否输出染色体编码(y/n):",100,210,20);
   printstrings=1;
   gscanf(320,210,9,15,4,"%s", answer);
    if(strncmp(answer,"n",1) == 0) printstrings = 0;
   setcolor(9);
   disp_hz16("最大世代数(100-300):",100,240,20);
   gscanf(320,240,9,15,4,"%d", &maxgen);
   setcolor(9);
   disp_hz16("交叉率(0.2-0.9):",100,270,20);
   gscanf(320,270,9,15,5,"%f", &pcross);
   setcolor(9);
   disp_hz16("变异率(0.01-0.1):",100,300,20);
   gscanf(320,300,9,15,5,"%f", &pmutation);
}
void initpop()           /* 随机初始化种群 */
{
    int j, j1, k, stop;
    unsigned mask = 1;
    for(j = 0; j < popsize; j++)
    {
        for(k = 0; k < chromsize; k++)
        {
            oldpop[j].chrom[k] = 0;
            if(k == (chromsize-1))
                stop = lchrom - (k*(8*sizeof(unsigned)));
            else
                stop =8*sizeof(unsigned);
            for(j1 = 1; j1 <= stop; j1++)
            {
               oldpop[j].chrom[k] = oldpop[j].chrom[k]<<1;
               if(flip(0.5))
                  oldpop[j].chrom[k] = oldpop[j].chrom[k]|mask;
            }
        }
        oldpop[j].parent[0] = 0;     /* 初始父个体信息 */
        oldpop[j].parent[1] = 0;
        oldpop[j].xsite = 0;
        objfunc(&(oldpop[j]));       /* 计算初始适应度*/
    }
}
void initreport()               /* 初始参数输出 */
{
    void   skip();
    skip(outfp,1);
    fprintf(outfp,"             基本遗传算法参数\n");
    fprintf(outfp," -------------------------------------------------\n");
    fprintf(outfp,"    种群大小(popsize)     =   %d\n",popsize);
    fprintf(outfp,"    染色体长度(lchrom)    =   %d\n",lchrom);
    fprintf(outfp,"    最大进化代数(maxgen)  =   %d\n",maxgen);
    fprintf(outfp,"    交叉概率(pcross)        = %f\n", pcross);
    fprintf(outfp,"    变异概率(pmutation)     = %f\n", pmutation);
    fprintf(outfp," -------------------------------------------------\n");
    skip(outfp,1);
    fflush(outfp);
}
void generation()
{
  int mate1, mate2, jcross, j = 0;
  /*  每代运算前进行预选 */
  preselect();
  /* 选择, 交叉, 变异 */
  do
    {
      /* 挑选交叉配对 */
      mate1 = select();
      mate2 = select();
      /* 交叉和变异 */
      jcross = crossover(oldpop[mate1].chrom, oldpop[mate2].chrom, newpop[j].chrom, newpop[j+1].chrom);
      mutation(newpop[j].chrom);
      mutation(newpop[j+1].chrom);
      /* 解码, 计算适应度 */
      objfunc(&(newpop[j]));
      /*记录亲子关系和交叉位置 */
      newpop[j].parent[0] = mate1+1;
      newpop[j].xsite = jcross;
      newpop[j].parent[1] = mate2+1;
      objfunc(&(newpop[j+1]));
      newpop[j+1].parent[0] = mate1+1;
      newpop[j+1].xsite = jcross;
      newpop[j+1].parent[1] = mate2+1;
      j = j + 2;
    }
  while(j < (popsize-1));
}
void initmalloc()              /*为全局数据变量分配空间 */
{
  unsigned nbytes;
  char  *malloc();
  int j;
  /* 分配给当前代和新一代种群内存空间 */
  nbytes = popsize*sizeof(struct individual);
  if((oldpop = (struct individual *) malloc(nbytes)) == NULL)
    nomemory("oldpop");
  if((newpop = (struct individual *) malloc(nbytes)) == NULL)
    nomemory("newpop");
  /* 分配给染色体内存空间 */
  nbytes = chromsize*sizeof(unsigned);
  for(j = 0; j < popsize; j++)
    {
      if((oldpop[j].chrom = (unsigned *) malloc(nbytes)) == NULL)
 nomemory("oldpop chromosomes");
      if((newpop[j].chrom = (unsigned *) malloc(nbytes)) == NULL)
 nomemory("newpop chromosomes");
    }
  if((bestfit.chrom = (unsigned *) malloc(nbytes)) == NULL)
    nomemory("bestfit chromosome");
}
void freeall()               /* 释放内存空间 */
{
  int i;
   for(i = 0; i < popsize; i++)
    {
      free(oldpop[i].chrom);
      free(newpop[i].chrom);
    }
  free(oldpop);
  free(newpop);
  free(bestfit.chrom);
   }
void nomemory(string)        /* 内存不足,退出*/
  char *string;
{
  fprintf(outfp,"malloc: out of memory making %s!!\n",string);
  exit(-1);
}
void report()                /* 输出种群统计结果 */
{
    void  repchar(), skip();
    void  writepop(), writestats();
    repchar(outfp,"-",80);
    skip(outfp,1);
    if(printstrings == 1)
    {
        repchar(outfp," ",((80-17)/2));
        fprintf(outfp,"模拟计算统计报告  \n");
        fprintf(outfp, "世代数 %3d", gen);
        repchar(outfp," ",(80-28));
        fprintf(outfp, "世代数 %3d\n", (gen+1));
        fprintf(outfp,"个体  染色体编码");
        repchar(outfp," ",lchrom-5);
        fprintf(outfp,"适应度    父个体 交叉位置  ");
        fprintf(outfp,"染色体编码 ");
        repchar(outfp," ",lchrom-5);
        fprintf(outfp,"适应度\n");
        repchar(outfp,"-",80);
        skip(outfp,1);
        writepop(outfp);
        repchar(outfp,"-",80);
        skip(outfp,1);
     }
    fprintf(outfp,"第 %d 代统计: \n",gen);
    fprintf(outfp,"总交叉操作次数 = %d, 总变异操作数 = %d\n",ncross,nmutation);
    fprintf(outfp," 最小适应度:%f 最大适应度:%f  平均适应度 %f\n", min,max,avg);
    fprintf(outfp," 迄今发现最佳个体 =>  所在代数: %d  ", bestfit.generation);
    fprintf(outfp," 适应度:%f  染色体:", bestfit.fitness);
    writechrom((&bestfit)->chrom);
    fprintf(outfp," 对应的变量值: %f", bestfit.varible);
    skip(outfp,1);
    repchar(outfp,"-",80);
    skip(outfp,1);  
}
void writepop()
{
    struct individual *pind;
    int j;
    for(j=0; j<popsize; j++)
    {
        fprintf(outfp,"%3d)  ",j+1);
        /* 当前代个体 */
        pind = &(oldpop[j]);
        writechrom(pind->chrom);
        fprintf(outfp,"  %8f | ", pind->fitness);
        /* 新一代个体 */
        pind = &(newpop[j]);
        fprintf(outfp,"(%2d,%2d)   %2d   ",
        pind->parent[0], pind->parent[1], pind->xsite);
        writechrom(pind->chrom);
        fprintf(outfp,"  %8f\n", pind->fitness);
    }
}
void writechrom(chrom)           /* 输出染色体编码 */
unsigned *chrom;
{
    int j, k, stop;
    unsigned mask = 1, tmp;
    for(k = 0; k < chromsize; k++)
    {
        tmp = chrom[k];
        if(k == (chromsize-1))
            stop = lchrom - (k*(8*sizeof(unsigned)));
        else
            stop =8*sizeof(unsigned);
        for(j = 0; j < stop; j++)
        {
            if(tmp&mask)
                fprintf(outfp,"1");
            else
                fprintf(outfp,"0");
            tmp = tmp>>1;
        }
    }
}
void preselect()
{
    int j;
    sumfitness = 0;
    for(j = 0; j < popsize; j++) sumfitness += oldpop[j].fitness;
}
int select()                    /* 轮盘赌选择*/
{
    extern float randomperc();
    float sum, pick;
    int i;
    pick = randomperc();
    sum = 0;
    if(sumfitness != 0)
    {
        for(i = 0; (sum < pick) && (i < popsize); i++)
            sum += oldpop[i].fitness/sumfitness;
    }
    else
        i = rnd(1,popsize);
    return(i-1);
}
void statistics(pop)  /* 计算种群统计数据 */
struct individual *pop;
{
    int i, j;
    sumfitness = 0.0;
    min = pop[0].fitness;
    max = pop[0].fitness;
    /* 计算最大、最小和累计适应度 */
    for(j = 0; j < popsize; j++)
    {
        sumfitness = sumfitness + pop[j].fitness;            
        if(pop[j].fitness > max) max = pop[j].fitness;        
        if(pop[j].fitness < min) min = pop[j].fitness;         
        /* new global best-fit individual */
        if(pop[j].fitness > bestfit.fitness)
   {
    for(i = 0; i < chromsize; i++)
     bestfit.chrom[i]      = pop[j].chrom[i];
            bestfit.fitness    = pop[j].fitness;
            bestfit.varible   = pop[j].varible;  
            bestfit.generation = gen;
   }
      }
    /* 计算平均适应度 */
    avg = sumfitness/popsize;
}
void title()
{
  settextstyle(0,0,4);
  gprintf(110,15,4,0,"SGA Optimizer");
  setcolor(9);
  disp_hz24("基本遗传算法",220,60,25);
}
void repchar (outfp,ch,repcount)
FILE *outfp;
char *ch;
int repcount;
{
    int j;
    for (j = 1; j <= repcount; j++) fprintf(outfp,"%s", ch);
}
void skip(outfp,skipcount)
FILE *outfp;
int skipcount;
{
    int j;
    for (j = 1; j <= skipcount; j++) fprintf(outfp,"\n");
}
void objfunc(critter)            /* 计算适应度函数值 */
struct individual *critter;
{
    unsigned mask=1;
    unsigned bitpos;
    unsigned tp;
    double pow(), bitpow ;
    int j, k, stop;
    critter->varible = 0.0;
    for(k = 0; k < chromsize; k++)
    {
        if(k == (chromsize-1))
            stop = lchrom-(k*(8*sizeof(unsigned)));
        else
            stop =8*sizeof(unsigned);
        tp = critter->chrom[k];
        for(j = 0; j < stop; j++)
        {
            bitpos = j + (8*sizeof(unsigned))*k;
            if((tp&mask) == 1)
            {
                bitpow = pow(2.0,(double) bitpos);
                critter->varible = critter->varible + bitpow;
            }
            tp = tp>>1;
        }
    }
    critter->varible =-1+critter->varible*3/(pow(2.0,(double)lchrom)-1);
    critter->fitness =critter->varible*sin(critter->varible*10*atan(1)*4)+2.0;
}
void  mutation(unsigned *child)   /*变异操作*/
{
    int j, k, stop;
    unsigned mask, temp = 1;
    for(k = 0; k < chromsize; k++)
    {
        mask = 0;
        if(k == (chromsize-1))
            stop = lchrom - (k*(8*sizeof(unsigned)));
        else
            stop = 8*sizeof(unsigned);
        for(j = 0; j < stop; j++)
        {
            if(flip(pmutation))
            {
                mask = mask|(temp<<j);
                nmutation++;
            }
        }
        child[k] = child[k]^mask;
    }
}
int crossover (unsigned *parent1, unsigned *parent2, unsigned *child1, unsigned *child2)
/* 由两个父个体交叉产生两个子个体 */
{
    int j, jcross, k;
    unsigned mask, temp;
    if(flip(pcross))
    {
        jcross = rnd(1 ,(lchrom - 1));/* Cross between 1 and l-1 */
        ncross++;
        for(k = 1; k <= chromsize; k++)
        {
            if(jcross >= (k*(8*sizeof(unsigned))))
            {
                child1[k-1] = parent1[k-1];
                child2[k-1] = parent2[k-1];
            }
            else if((jcross < (k*(8*sizeof(unsigned)))) && (jcross > ((k-1)*(8*sizeof(unsigned)))))
            {
                mask = 1;
                for(j = 1; j <= (jcross-1-((k-1)*(8*sizeof(unsigned)))); j++)
                {
                    temp = 1;
                    mask = mask<<1;
                    mask = mask|temp;
                }
                child1[k-1] = (parent1[k-1]&mask)|(parent2[k-1]&(~mask));
                child2[k-1] = (parent1[k-1]&(~mask))|(parent2[k-1]&mask);
            }
            else
            {
                child1[k-1] = parent2[k-1];
                child2[k-1] = parent1[k-1];
            }
        }
    }
    else
    {
        for(k = 0; k < chromsize; k++)
        {
            child1[k] = parent1[k];
            child2[k] = parent2[k];
        }
        jcross = 0;
    }
    return(jcross);
}
void advance_random()          /* 产生55个随机数 */
{
    int j1;
    double new_random;
    for(j1 = 0; j1 < 24; j1++)
    {
        new_random = oldrand[j1] - oldrand[j1+31];
        if(new_random < 0.0) new_random = new_random + 1.0;
        oldrand[j1] = new_random;
    }
    for(j1 = 24; j1 < 55; j1++)
    {
        new_random = oldrand [j1] - oldrand [j1-24];
        if(new_random < 0.0) new_random = new_random + 1.0;
        oldrand[j1] = new_random;
    }
}
int flip(float prob)          /* 以一定概率产生0或1 */
{
    float randomperc();
    if(randomperc() <= prob)
        return(1);
    else
        return(0);
}
void randomize()            /* 设定随机数种子并初始化随机数发生器 */
{
    float randomseed;
    int j1;
    for(j1=0; j1<=54; j1++)
      oldrand[j1] = 0.0;
    jrand=0;
      do
        {
            setcolor(9);
              disp_hz16("随机数种子[0-1]:",100,330,20);
              gscanf(320,330,9,15,4,"%f", &randomseed);
         }
        while((randomseed < 0.0) || (randomseed > 1.0));
    warmup_random(randomseed);
}
double randomnormaldeviate()         /* 产生随机标准差 */
{
    double sqrt(), log(), sin(), cos();
    float randomperc();
    double t, rndx1;
    if(rndcalcflag)
    {   rndx1 = sqrt(- 2.0*log((double) randomperc()));
        t = 6.2831853072 * (double) randomperc();
        rndx2 = rndx1 * sin(t);
        rndcalcflag = 0;
        return(rndx1 * cos(t));
    }
    else
    {
        rndcalcflag = 1;
        return(rndx2);
    }
}
float randomperc()            /*与库函数random()作用相同, 产生[0,1]之间一个随机数 */
{
    jrand++;
    if(jrand >= 55)
    {
        jrand = 1;
        advance_random();
    }
    return((float) oldrand[jrand]);
}
int rnd(low, high)           /*在整数low和high之间产生一个随机整数*/
int low,high;
{
    int i;
    float randomperc();
    if(low >= high)
        i = low;
    else
    {
        i = (randomperc() * (high - low + 1)) + low;
        if(i > high) i = high;
    }
    return(i);
}

void warmup_random(float random_seed)       /* 初始化随机数发生器*/
{
    int j1, ii;
    double new_random, prev_random;
    oldrand[54] = random_seed;
    new_random = 0.000000001;
    prev_random = random_seed;
    for(j1 = 1 ; j1 <= 54; j1++)
    {
        ii = (21*j1)%54;
        oldrand[ii] = new_random;
        new_random = prev_random-new_random;
        if(new_random<0.0) new_random = new_random + 1.0;
        prev_random = oldrand[ii];
    }
    advance_random();
    advance_random();
    advance_random();
    jrand = 0;
}

main(argc,argv)           /*  主程序  */
int argc;
char *argv[];
{
    struct individual *temp;
    FILE   *fopen();
    void   title();
    char   *malloc();
        if((outfp = fopen(argv[1],"w")) == NULL)
        {
           fprintf(stderr,"Cannot open output file %s\n",argv[1]);
            exit(-1);
        }
     g_init();
     setcolor(9);
     title();
     disp_hz16("输入遗传算法执行次数(1-5):",100,120,20);
     gscanf(320,120,9,15,4,"%d",&maxruns);
     for(run=1; run<=maxruns; run++)
    {
        initialize();
        for(gen=0; gen<maxgen; gen++)
        {
         fprintf(outfp,"\n第 %d / %d 次运行: 当前代为 %d, 共 %d 代\n", run,maxruns,gen,maxgen);
            /* 产生新一代 */
            generation();
            /* 计算新一代种群的适应度统计数据 */
            statistics(newpop);
            /* 输出新一代统计数据 */
            report();
            temp = oldpop;
            oldpop = newpop;
            newpop = temp;
        }
        freeall();
    }
}
搜索更多相关主题的帖子: 算法 遗传 
2008-06-12 20:06
hujia358
Rank: 1
等 级:新手上路
帖 子:3
专家分:0
注 册:2008-6-12
收藏
得分:0 
提示是没有graph.c不知道怎么办,高手来帮帮忙啊
2008-06-12 20:07
ranmomo
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2008-6-19
收藏
得分:0 
这个遗传算法的源程序压缩包中有一个graph.c的c文件,是一个作者编写的一个图形显示函数库。代码如下:
#define ESC 0x1b
#include <conio.h>
#include <process.h>
#include <io.h>
#include <dos.h>
int mouse_text_x;
int mouse_text_y;
int mouse_grph_x;
int mouse_grph_y;
int mouse_initialized=0;
static int low_resolution=0;
static pre_cursor_state=0;
static char far *bios_video_area=(char far *)0x00400049L;

extern void mouse_on(int restoreflag);
extern void mouse_off(int tempflag);

void read_clib24(unsigned int hz_code,int x1,int y1,FILE *stream)
 /* 读24点阵汉字字库 */
{
  register  int i,j;
  unsigned int gjqwm;
  struct{
  unsigned int bit0:1;
  unsigned int bit1:1;
  unsigned int bit2:1;
  unsigned int bit3:1;
  unsigned int bit4:1;
  unsigned int bit5:1;
  unsigned int bit6:1;
  unsigned int bit7:1;
  }sp[72];
  union{
  struct {
  unsigned int bit0:1;
  unsigned int bit1:1;
  unsigned int bit2:1;
  unsigned int bit3:1;
  unsigned int bit4:1;
  unsigned int bit5:1;
  unsigned int bit6:1;
  unsigned int bit7:1;
  }s;
  unsigned char byte;}cc;
  long kk;
  gjqwm=hz_code-1500;
  kk=(gjqwm/100-1)*94+(gjqwm%100);
  kk=(kk-1)*72;
  fseek(stream,kk,SEEK_SET);
  fread(sp,1,72,stream);
  for(i=0;i<72;i=i+3)
  {
  for(j=2;j>=0;j--)
   {
    cc.s.bit7=sp[j+i].bit0;
    cc.s.bit6=sp[j+i].bit1;
    cc.s.bit5=sp[j+i].bit2;
    cc.s.bit4=sp[j+i].bit3;
    cc.s.bit3=sp[j+i].bit4;
    cc.s.bit2=sp[j+i].bit5;
    cc.s.bit1=sp[j+i].bit6;
    cc.s.bit0=sp[j+i].bit7;
    setlinestyle(USERBIT_LINE,cc.byte,1);
    line(x1,y1+23-(2-j)*8,x1,y1+23-(2-j)*8-7);
    }
    x1=x1+1;
  }
}

int disp_hz24(unsigned char *msg,int x1,int y1,int delt) /* 显示汉字串 */
{
  FILE *stream;
  unsigned char g1,g2;
  unsigned  int hz_code;
  register  int i,j;
  settextjustify(CENTER_TEXT,CENTER_TEXT);
  if((stream=fopen("\\GA\\hzk24s","rb"))==NULL)
 {
  setlinestyle(SOLID_LINE,0,1);
  return 1;
 }
 for(;*msg;msg+=2)
   {
   g1=*msg-0xa0;
   g2=*(msg+1)-0xa0;
   hz_code=g1*100+g2;
   read_clib24(hz_code,x1,y1,stream);
   x1+=delt;
   }
  fclose(stream);
  setlinestyle(SOLID_LINE,0,1);
  return 0;
}

void read_clib16(unsigned int hz_code,int x1,int y1,FILE *stream)
 /* 读16点阵汉字字库 */
{
  register  int i,j;
  unsigned int gjqwm;
  unsigned char sp[32];
  unsigned long kk,k;
  gjqwm=hz_code;
  kk=(gjqwm/100-1)*94+(gjqwm%100);
  kk=(kk-1)*32;
  fseek(stream,kk,SEEK_SET);
  fread(sp,1,32,stream);
  for(i=0;i<32;i=i+2)
  {
    k=sp[i]*256+sp[i+1];
    setlinestyle(USERBIT_LINE,k,1);
    line(x1+15,y1,x1,y1);
    y1++;
  }
}

int disp_hz16(unsigned char *msg,int x1,int y1,int delt) /* 显示汉字串 */
{
  FILE *stream;
  unsigned char g1,g2;
  unsigned  int hz_code;
  register  int i,j;
  char msg_no_hz[1];
  settextjustify(CENTER_TEXT,CENTER_TEXT);
  if((stream=fopen("\\GA\\hzk16","rb"))==NULL)
 {
  setlinestyle(SOLID_LINE,0,1);
  return 1;
 }
next1: for(;*msg;msg+=2)
   {
  if(*msg<0xa0)
  {
   settextstyle(0,0,0);
   msg_no_hz[0]=*msg;
   msg_no_hz[1]=0;
   outtextxy(x1,y1+8,msg_no_hz);
   x1+=8;
   msg++;
  }
  if(*msg<0xa0)
  {
   settextstyle(0,0,0);
   msg_no_hz[0]=*msg;
   msg_no_hz[1]=0;
   outtextxy(x1,y1+8,msg_no_hz);
   x1+=8;
   msg++;
   goto next1;
  }
   g1=*msg-0xa0;
   g2=*(msg+1)-0xa0;
   hz_code=g1*100+g2;
   read_clib16(hz_code,x1,y1,stream);
   x1+=delt;
  }
  fclose(stream);
  setlinestyle(SOLID_LINE,0,1);
  return 0;
}


int gprintf( int xloc,int yloc,int fc,int bc,char *fmt,...)
  {
   va_list argptr;
   char str[150];
   int cnt;
   struct  viewporttype view;
   int xp,yp;
   getviewsettings(&view);
   va_start(argptr,fmt);
   cnt=vsprintf(str,fmt,argptr);
   va_end(argptr);
   setfillstyle(1,bc);
   bar(xloc,yloc,xloc+8*strlen(str),yloc+8);
   settextjustify(LEFT_TEXT,TOP_TEXT);
   setcolor(fc);
   outtextxy(xloc,yloc,str);
   return(cnt);
}
void mouse(int *m1,int *m2,int *m3,int *m4)
{
    union REGS inregs, outregs;
    inregs.x.ax=*m1;
    inregs.x.bx=*m2;
    inregs.x.cx=*m3;
    inregs.x.dx=*m4;
    int86(0x33,&inregs,&outregs);
    *m1=outregs.x.ax;
    *m2=outregs.x.bx;
    *m3=outregs.x.cx;
    *m4=outregs.x.dx;
}
int check_mouse_driver(int need_mouse)
{
   void far *address;
   address=getvect(0x33);
   if((address==NULL||*(unsigned char *) address==0xcf))
   {
     if(need_mouse)
     { printf("Mouse driver NOT installed\n");
       exit(1);
      }
     else
       return 0;
      }
       return 1;
}
static void set_mouse_posn(int *x,int *y)
{
  if(low_resolution)  *x>>=1;
  mouse_grph_x=*x;
  mouse_grph_y=*y;
  mouse_text_x=*x/8+1;
  mouse_text_y=*y/8+1;
}

  static int low_res_mode(int gd,int gm)
{
  if((gd==1||gd==2||gd==8)&&(gm>=0&&gm<=3))
  return 1;
  return 0;
}
int  mouse_reset(void)
{
  int x1,m1,m2,m3,m4;
  mouse_off(1);
  m1=0;
  mouse(&m1,&m2,&m3,&m4);
  set_mouse_posn(&m3,&m4);
  return m1;
}
void move_mouse(int x,int y)
{
  int m1,m2,m3,m4;
  if(mouse_initialized) return;
  m1=4;
  m3=x;m4=y;
  mouse(&m1,&m2,&m3,&m4);
  set_mouse_posn(&m3,&m4);
}
void mouse_on(int restoreflag)
{
  int m1,m2,m3,m4;
  if(mouse_initialized)
  {
  if(!restoreflag||pre_cursor_state)
  {
   m1=1;
   mouse(&m1,&m2,&m3,&m4);
   pre_cursor_state=1;
  }
 }
}
void mouse_off(int tempflag)
{
  int m1,m2,m3,m4;
  if(mouse_initialized)
  {
  if(pre_cursor_state)
  {
   m1=2;
   mouse(&m1,&m2,&m3,&m4);
  if(!tempflag)
   pre_cursor_state=0;
  }
 }
}

int init_mouse(int need_mouse,int gd,int gm)
{
   int m1;
   mouse_initialized=0;
   if(check_mouse_driver(need_mouse))
   {
    if(gd==7) *bios_video_area=6;
    if(low_res_mode(gd,gm))
      low_resolution=1;
     m1=mouse_reset();
     if(m1)
    {  mouse_initialized=1;
       move_mouse(0,0);
       mouse_on(0);
     }
  else
   {
  if(need_mouse)
   {
    printf("ERROR activating mouse...\n");
    exit(1);
   }
  }
 }
 }

int button_press(int b)
{
  int m1,m2,m3,m4;
  if(mouse_initialized)
  {
   m1=5;
   m2=b;
   mouse(&m1,&m2,&m3,&m4);
   set_mouse_posn(&m3,&m4);
   if(m2) return 1;
  }
   return 0;
}
int button_release(int b)
{
  int m1,m2,m3,m4;
  if(mouse_initialized)
  {
   m1=6;
   m2=b;
   mouse(&m1,&m2,&m3,&m4);
   set_mouse_posn(&m3,&m4);
   if(m2) return 1;
  }
   return 0;
}

int button_state()
{
  int m1,m2,m3,m4;
  if(mouse_initialized)
  {
   m1=3;
   mouse(&m1,&m2,&m3,&m4);
   set_mouse_posn(&m3,&m4);
   return m2;
  }
   return 0;
}
void mouse_grph_posn(int *x,int *y)
{
  int m1,m2;
  if(mouse_initialized)
  {
   m1=3;
   mouse(&m1,&m2,x,y);
   set_mouse_posn(x,y);
  }
  else
  { *x=*y=0;
  }
   return;
}
void mouse_txt_posn(int *x,int *y)
{
   mouse_grph_posn(x,y);
  *x=mouse_text_x;
  *y=mouse_text_y;
  return;
}
int mouse_trigger(int button_dir)
{
  int k=0;
  union inkey
   {
     char ch[2];
      int i;
      }c;
   if(bioskey(1))
   {
     c.i=bioskey(0);
       if(c.ch[0])
    k=c.ch[0];
       else
       k=c.ch[1];
    }
    else
    {
    k=0;
    if(button_dir)
      {
    if(button_press(0)) k=0xFF01;
    else if(button_press(1)) k=0xFF02;
      }
      {
    if(button_release(0)) k=0xFF11;
    else if(button_release(1)) k=0xFF12;
      }
    }
    return k;
  }


  void g_init()              /*  图形初始化  */
{  int g_driver,g_mode;
   g_driver=DETECT;
   initgraph(&g_driver,&g_mode,"");
   if(grOk !=graphresult()) exit(1);
}

void g_pset(x,y,col)          /*  描点  */
int x,y,col;
{ putpixel(x,y,col);
}

void g_line(x1,y1,x2,y2,col)  /*  绘直线  */
int x1,y1,x2,y2,col;
{  setcolor(col);
   setlinestyle(0,1,0);
   line(x1,y1,x2,y2);
}

void g_circle(cx,cy,rx,ry,col)   /*   绘圆   */
int cx,cy,rx,ry,col;
{
  setcolor(col);
  ellipse(cx,cy,0,360,rx,ry);
}

void g_rectangle(x1,y1,x2,y2,col,fill)   /*    绘矩形  */
int x1,y1,x2,y2,col,fill;
{
if(fill!=1)
  { setcolor(col);
  setlinestyle(0,1,0);
  rectangle(x1,y1,x2,y2);
  }
else
{
setfillstyle(1,col);
bar(x1,y1,x2,y2);
}
}

void g_cls()         /*  清屏  */
{
cleardevice();
}

void g_text(x,y,col,text)    /*   写文字  */
int x,y,col;
char *text;
{
setcolor(col);
settextstyle(0,0,1);
outtextxy(x,y,text);
}

int g_pget(x,y)           /*  取得点颜色  */
int x,y;
{ int color;
color=getpixel(x,y);
return(color);
}

 int gscanf(int x,int y,int fore,int back,int length,char *fmt,...)
{
   va_list argptr;
   char key[40];
   int xp,yp,temp;
   int i=0,xx=x,j;
   char string[10];
   char c[1];
   union inkey{
     char ch[2];
     int i;
    }cc;
   setwritemode(1);
   va_start(argptr,fmt);
   setcolor(15);
   mouse_off(0);
   line(x,y,x,y+8);
   mouse_on(0);
   setcolor(fore);
   setfillstyle(1,back);
   settextjustify(0,2);
   settextstyle(0,0,1);
   do{
    circl:
     setcolor(15);
     mouse_off(0);
     line(x,y,x,y+8);
     mouse_on(0);
     if(button_press(0))
     {
      cc.ch[0]=0x0d;
      goto press_m_k;
     }
     if(button_press(0))
     {
      cc.ch[0]=0x1b;
      goto press_m_k;
     }
     if(button_press(1))
     {
       cc.ch[0]=ESC;
       goto press_m_k;
     }
     if(bioskey(1))
       {
          cc.i=bioskey(0);
       }
      else
       { delay(100);
         goto  circl;
       }
  press_m_k:
       setcolor(15);
       mouse_off(0);
       line(x,y,x,y+8);
       mouse_on(0);
       if(cc.ch[0])
       {
         temp=key[i]=c[0]=cc.ch[0];
         c[1]='\0';
         switch(temp)
          {
            case  0x0d:  goto  next;
            case  0x1b:
               setcolor(back);
               setwritemode(0);
               mouse_off(0);
               line(x,y,x,y+8);
               mouse_on(0);
               key[0]='\0';
               vsscanf(key,fmt,argptr);
               va_end(argptr);
               return 1;
            case  75*256:
        case   8:
           x-=8;
               if(x<=xx) x=xx;
               setfillstyle(1,back);
               mouse_off(0);
           bar(x,y,x+8,y+8);
           setcolor(15);
               line(x,y,x,y+8);
               mouse_on(0);
               i=i-2;
               if(i<0)  i=-1;
               break;
            defaut:
               if(cc.ch[0])
        {
        setcolor(15);
        mouse_off(0);
                line(x,y,x,y+8);
        setfillstyle(1,back);
                bar(x,y,x+8,y+8);
                setcolor(fore);
                settextstyle(0,0,1);
        outtextxy(x,y,c);
                mouse_on(0);
                x+=8;
                }
          break;
           }
        i++;
        }
      } while((i<length)&& (i>=0));
 next:
            setcolor(back);
            setwritemode(0);
            mouse_off(0);
            line(x,y,x,y+8);
            mouse_on(0);
            key[i]='\0';
            vsscanf(key,fmt,argptr);
            va_end(argptr);
            settextstyle(1,0,2);
            return 0;
  }
把上面的代码作为graph.c文件即可,但是我将源程序在tc中编译是,结果是Cannot open output file,应该是要打开的文件没有建立,请教高手,应该如何建立这个文件
2008-06-22 21:45
StarWing83
Rank: 8Rank: 8
来 自:仙女座大星云
等 级:贵宾
威 望:19
帖 子:3951
专家分:748
注 册:2007-11-16
收藏
得分:0 
那不正好是绝配么?

专心编程………
飞燕算法初级群:3996098
我的Blog
2008-06-22 22:20
maguangzhi
Rank: 1
等 级:新手上路
帖 子:14
专家分:0
注 册:2008-10-30
收藏
得分:0 
贡献一个P2P并行遗传算法: http://maguangzhi.bokee.com
如题
2008-10-30 07:35
jfyh
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2014-10-27
收藏
得分:0 
醉了
2014-10-27 21:15
快速回复:大家来看看这个遗传算法程序C
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.020112 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved