OpenGL举例,MFC举例:画3条函数曲线

来源:互联网 发布:在线网络信托公司 编辑:程序博客网 时间:2024/06/08 09:48

感谢大家支持,超级玛丽的下载次数超过9000了!我最近码OpenGL,这是一个例子。画了三个等价无穷小曲线。主要代码如下:

 

#include "math01.h"

#define XSTEP (3.14/40)
#define XPOINT 0.02
#define POINTNUM 30

 

void DrawRect(GLfloat x, GLfloat y,GLfloat w, GLfloat h)
{
  glRectf(x,y,x+w,y+h);
}


void CALLBACK display(void)
{
 int i;

 glColor3f(0.0,0.3,0.0);
 DrawRect(-0.5,-0.5,1.0,1.0);

 // 两条坐标
 glColor3f(0.0,1.0,0.0);
 for(i=0;i<POINTNUM+10;i++)
 { 
  DrawRect(-1.0+i*XSTEP*2/3, -0.5,
   XPOINT,XPOINT);
 }
 for(i=0;i<POINTNUM+10;i++)
 { 
  DrawRect( -0.5,-1.0+i*XSTEP*2/3,
   XPOINT,XPOINT);
 }

 //sin
 glColor3f(1.0,0.0,0.0);
 for(i=0;i<POINTNUM;i++)
 {
  DrawRect(-0.5+i*XSTEP*2/3, -0.5+sin(i*XSTEP)*2/3,
   XPOINT,XPOINT);
 }

 //y=x
 glColor3f(1.0,1.0,0.0);
 for(i=0;i<POINTNUM;i++)
 {
  DrawRect(-0.5+i*XSTEP*2/3, -0.5+i*XSTEP*2/3,
   XPOINT,XPOINT);
 }
 
 //y=e(x)
 glColor3f(1.0,0.0,0.5);
 for(i=0;i<20;i++)
 {
  DrawRect(-0.5+i*XSTEP*2/3, -0.5+(E_Exp(i*XSTEP)-1)*2/3,
   XPOINT,XPOINT);
 }

 glFlush(); 
}

//////////////////////////////////////////////////////////////////////////////

 

//math01.h
//数学计算公式

#ifndef MYMATH01_H
#define MYMATH01_H

//x的n次方
float Mul(float x,int n);
int Jie(int n);
float E_Exp(float x);

float Mul(float x,int n)
{
 int i=0;
 float k=1;

 if(0==n)
  return 1;
 for(i=0;i<n;i++)
 {
  k*=x;
 }
 return k;
}

//n的阶乘
int Jie(int n)
{
 int k=1;

 if(0==n)
  return 1;
 for(;n>0;n--)
 {
  k*=n;
 }
 return k;

}

//e的x次方 麦克劳林级数,没有余项
float E_Exp(float x)
{
 int i;
 float sum=0;

 for(i=0;i<20;i++)
 {
  sum+=Mul(x,i)/Jie(i);
 }
 return sum;

}

#endif

 

//////////////////////////////////////////////////////////////////////////////////

//MFC版 CxxxxxDlg::OnPaint

 

  CPaintDC mydc(this); // device context for painting
  CPen pen1(PS_SOLID, 1, RGB(0,180,50));
  CPen pen2(PS_SOLID, 2, RGB(0,180,50));
  int i;
  float temp;

  mydc.MoveTo(0,350);
  mydc.LineTo(400,350);

  mydc.MoveTo(50,0);
  mydc.LineTo(50,400);
  
  // x取值范围 0, pi/2
  mydc.MoveTo(50,350);
  for(i=0;i<20;i++)
  {
   temp=i*3.14/40;
   mydc.LineTo(50+temp*XSCALE,350-sin(temp)*XSCALE);
  }
  
  mydc.MoveTo(50,350);
  for(i=0;i<20;i++)
  {
   temp=i*3.14/40;
   mydc.LineTo(50+temp*XSCALE,350-temp*XSCALE);
  }

  mydc.MoveTo(50,350);
  for(i=0;i<20;i++)
  {
   temp=i*3.14/40;
   mydc.LineTo(50+temp*XSCALE,350-(E_Exp(temp)-1)*XSCALE);
  }

  mydc.SelectObject(&pen1);
  // 1-cos x
  mydc.MoveTo(50,350);
  for(i=0;i<20;i++)
  {
   temp=i*3.14/40;
   mydc.LineTo(50+temp*XSCALE,350-(1-cos(temp))*XSCALE);
  }

  // squar(x)/2
  mydc.SelectObject(&pen2);
  mydc.MoveTo(50,350);
  for(i=0;i<20;i++)
  {
   temp=i*3.14/40;
   mydc.LineTo(50+temp*XSCALE,350-(temp*temp/2)*XSCALE);
  }
  
  CDialog::OnPaint();