1. 程式人生 > >OpenGL: 畫3條函式曲線

OpenGL: 畫3條函式曲線

感謝大家支援,超級瑪麗的下載次數超過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();