1 /*利用星号输出画一个任意大小的圆*/
2 #include <math.h>
3 #include <stdio.h>
4
5 int max(int a, int b)
6 {
7 return a > b ? a : b;
8 }
9
10 void print_char(int x1, int x2)
11 {
12 int i;
13 // 计算这一行的宽度,终端最多显示80列
14 int n = max(x1, x2) + 1;
15 n = n > 80 ? 80 : n;
16 for (i = 0; i < n; i++)
17 {
18 if (i == x1 || i == x2)
19 printf("*");
20 else
21 printf(" ");
22 }
23 printf("\n");
24 }
25
26 void print_circle(int r)
27 {
28 int x1, x2, y;
29 int d = 2 * r;
30 int offset;
31 for(y = 0; y <= d; y++)
32 {
33 /*终端字符宽高比为2:1*/
34 offset = (int)(0.5 + sqrt((double)(r*r - (y-r)*(y-r)))*2.0);
35 x1 = d - offset;
36 x2 = d + offset;
37 print_char(x1, x2);
38 }
39 }
40
41 int main(int argn, char *argv[])
42 {
43 int r = 5;
44 if (argn > 1)
45 r = atoi(argv[1]);
46
47 print_circle(r);
48 return 0;
49 }
50