轉自 EasyX,不過我重構了代碼。
運行結果:
來源程式:
1 // MandelbrotSet.cpp 2 3 #include "graphics.h" 4 #include <conio.h> 5 6 struct Complex 7 { 8 double re; 9 double im;10 11 public:12 Complex operator * (const Complex &other) const13 {14 Complex c;15 c.re = this->re * other.re - this->im * other.im;16 c.im = this->im * other.re + this->re * other.im;17 return c;18 }19 20 Complex operator + (const Complex &other) const21 {22 Complex c;23 c.re = this->re + other.re;24 c.im = this->im + other.im;25 return c;26 }27 };28 29 void main()30 {31 // 初始化繪圖視窗32 initgraph(640, 480);33 34 /////////////////////////////////////////////////35 // 繪製 Mandelbrot Set (曼德布洛特集)36 /////////////////////////////////////////////////37 Complex z, c;38 for(int x = 0; x < 640; x++)39 {40 c.re = -2.1 + (1.1 - -2.1) * (x / 640.0);41 for(int y = 0; y < 480; y++)42 {43 c.im = -1.2 + (1.2 - -1.2) * (y / 480.0);44 z.re = z.im = 0;45 int k;46 for(k = 0; k < 180; k++)47 {48 if ( z.re * z.re + z.im * z.im > 4.0 ) break;49 z = z * z + c;50 }51 putpixel(x, y, (k >= 180) ? 0 : HSLtoRGB((float)((k << 5) % 360), 1.0, 0.5));52 }53 }54 55 // 按任意鍵退出56 _getch();57 closegraph();58 }