如图,求其中有几个正方形,因为中间两个田字是单独的,所以我们抛去不谈,单独编程求4*4个格子中有几个正方形,或者引申下求n*n个格子中有几个正方形,源代码如下:

 1 #include <stdio.h>
 2 
 3 int square(int n){
 4     int total = 0;
 5     int m = n;
 6 
 7     if(n == 1)
 8         return 1;
 9     else{
10         while((n-1) > 1){
11             total += (n-1)*(n-1);//规律:超过田字格,的三格和以上都是(n-1)平方的规律,如:三格中有(3-1)^2个田字格
12             n--;
13         }
14     }
15     total += m*m + 1;   //计算单个格子正方形,和一个整个大正方形
16 
17     return total;
18 }
19 int main(void){
20     int n, m;
21     int total = 0;
22     printf("Please input the numbers of edges: ");
23     scanf("%d", &n);
24     printf("\nTotal: %d\n", square(n));
25 
26     return 0;
27 }

 方法二:

 1 #include <stdio.h>
 2 
 3 void square(int a, int b, int n, int * total){
 4     do{
 5         a++;
 6         b++;
 7         (*total)++;
 8     }while(a < n && b < n);
 9 
10     return ;
11 }
12 
13 int main(void){
14     int n;
15     int total = 0;
16     printf("Please input the numbers of edges: ");
17     scanf("%d", &n);
18     for(int i = 0; i < n; i++)
19         for(int j = 0; j < n; j++){
20             square(i, j, n, &total);
21         }
22     printf("\nTotal: %d\n", total);
23 
24     return 0;
25 }