写37行代码就为了画个围棋棋盘值不值?有更简洁的算法吗?
#include<graphics.h> #include<conio.h> #define LEN 30 // 每格间的距离 int main() { int x, y; initgraph(660, 660); // 背景上色 setcolor(BROWN); for(y = 0; y < 660; y++) line(0, y, 660, y); // 绘制边框 setcolor(BLACK); line(35, 35, 45+540, 35); line(35, 45+540, 45+540, 45+540); line(35, 35, 35, 45+540); line(45+540, 35, 45+540, 45+540); for(y = 40; y<=40+LEN*18; y+=LEN) line(40, y, 40+LEN*18, y); for(x = 40; x<=40+LEN*18; x+=LEN) line(x, 40, x, 40+LEN*18); // 绘制黑点 setfillcolor(BLACK); fillcircle(40+3*LEN, 40+3*LEN, 2); fillcircle(40+9*LEN, 40+3*LEN, 2); fillcircle(40+15*LEN, 40+3*LEN, 2); fillcircle(40+3*LEN, 40+9*LEN, 2); fillcircle(40+9*LEN, 40+9*LEN, 2); fillcircle(40+15*LEN, 40+9*LEN, 2); fillcircle(40+3*LEN, 40+15*LEN,2); fillcircle(40+9*LEN, 40+15*LEN,2); fillcircle(40+15*LEN, 40+15*LEN,2); getch(); closegraph(); return 0;
很显然, 这里可以用for循环来帮你做些事情。
for (int i = 1; i <= 3; i++) for (int j = 1; j <= 3; j++) { fillcircle(40+3*i*LEN, 40+3*j*LEN, 2); }
一般重复行的操作都是通过循环来实现的。 只要是有规律的项目都是可以实现的。
不值。
int x[3] = { 3, 9, 15 };
for ( int i = 0; i < 3; ++i )
{
fillcircle( 40 + x[0] * LEN, 40 + x[i] * LEN, 2 );
fillcircle( 40 + x[1] * LEN, 40 + x[i] * LEN, 2 );
fillcircle( 40 + x[2] * LEN, 40 + x[i] * LEN, 2 );
}