练习02-26-01 输出“魔方阵”,所谓“魔方阵”是这样的方阵,它的每一行、每一列和对角线之和均相等
Today is a meaningful day for me. Because I will check out the scores of the forth entering exam for the post-graduate. Frankly, I am so thrilled that I cannot have the brave to browser the website. In my unconscious mind, it is horror for me to loose this opportunity to onboard. Anyway, I wish I can got a satisfied results. Good luck.
输出样例:
enter the odd from 1-15
5
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
the sum of row = 325;the sum of column = 325;the sum of diagonal = 325
--------------------------------
Process exited after 2.255 seconds with return value 0
请按任意键继续. . .
代码亮点:(如何让用户输入你想要输入的奇数)
p=1; //条件选择变量
while(p==1){
printf("enter the odd from 1-15\n");
scanf("%d",&n);
if((n>0)&&(n<=15)&&(n%2)!=0){
p=0;
}
}
锻炼的能力:(对于多个不同条件应用选择语句进行排序的能力)
- 首先判断这个数是不是1行,第n列
- 判断行数是否为1,若为1将其改为n,并且判断a[i][j]是否为零,若为非零,将其i,j复原,并且再将i+1;
- 判断列数是否为n,若为n,则将其置为1,并且判断a[i][j]是否为零,若为非零,将其i,j复原,并且再将i+1;
- 如果上面的都不是,则i=i-1;j=j+1;并且判断a[i][j]是否为零,若为非零,将其i,j复原,并且再将i+1;
//输出“魔方阵”
#include<stdio.h>
int main()
{
int a[16][16],i,j,k,p,n;
int sum1=0,sum2=0,sum=0;
p=1;
while(p==1){
printf("enter the odd from 1-15\n");
scanf("%d",&n);
if((n>0)&&(n<=15)&&(n%2)!=0){
p=0;
}
}
for(i=1;i<=n;++i){
for(j=1;j<=n;++j){
a[i][j]=0;
}
}
i=1;
j=(n+1)/2;
a[i][j]=1;
for(k=2;k<=n*n;++k){
if((i==1)&&(j==n)){
//printf("yes");
i=i+1;
} else if(i==1){
i=n;
j+=1;
if(a[i][j]!=0){
i=2;
j-=1;
}
}else if(j==n){
j=1;
i-=1;
if(a[i][j]!=0){
i+=1;
j=n;
}
}else{
i-=1;
j+=1;
if(a[i][j]!=0){
i+=2;
j-=1;
}
}
a[i][j]=k;
}
for(i=1;i<=n;++i){
for(j=1;j<=n;++j){
printf("%3d",a[i][j]);
sum1+=a[1][j];
sum2+=a[i][1];
sum+=a[i][i];
}
putchar('\n');
}
printf("\nthe sum of row = %d;the sum of column = %d;the sum of diagonal = %d ",sum1,sum2,sum);
return 0;
}