一、程序填空题
在此程序中,函数fun的功能是:判定形参a所指的N*N(规定N为奇数)的矩阵是否是”幻方”,若是,函数返回值为1;若不是,函数返回值为0。”幻方”的判定条件是:矩阵每行、每列、主对角线及反对角线上元素之和都相等。
例如,以下3*3的矩阵就是一个”幻方”:
#include <stdio.h>
#define N 3
int fun(int (*a)[N])
{ int i,j,m1,m2,row,colum;
m1=m2=0;
for(i=0; i<N; i++)
{ j=N-i-1; m1+=a[i][i]; m2+=a[i][j]; }
if(m1!=m2) return 0;
for(i=0; i<N; i++) {
/**********found**********/
row=colum= __1__;
for(j=0; j<N; j++)
{ row+=a[i][j]; colum+=a[j][i]; }
/**********found**********/
if( (row!=colum) __2__ (row!=m1) ) return 0;
}
/**********found**********/
return __3__;
}
void main()
{ int x[N][N],i,j;
printf("Enter number for array:\n");
for(i=0; i<N; i++)
for(j=0; j<N; j++) scanf("%d",&x[i][j]);
printf("Array:\n");
for(i=0; i<N; i++)
{ for(j=0; j<N; j++) printf("%3d",x[i][j]);
printf("\n");
}
if(fun(x)) printf("The Array is a magic square.\n");
else printf("The Array isn't a magic square.\n");
}
答案:(1) 0 (2) || (3) 1
二、程序修改题
在此程序中,函数fun的功能是:传入一个整数m,计算如下公式的值。
例如,若输入5,则应输出-0.283333。
#include <stdlib.h>
#include <conio.h>
#include <stdio.h>
double fun(int m)
{
double t=1.0;
int i;
for(i=2;i<=m;i++)
/*************found**************/
t=1.0-1/i;
/*************found**************/
;
}
void main()
{int m;
system("CLS");
printf("\nPlease enter 1 integer numbers:\n");
scanf("%d",&m);
printf("\n\nThe result is %1f\n",
fun(m));
}
答案:(1) t-=1.0/i; (2) return t;
三、程序设计题
在此程序中,编写一个函数,用来删除字符串中的所有空格。
例如,输入asd af aa z67,则输出为asdafaaz67。
#include <stdio.h>
#include <ctype.h>
#include <conio.h>
#include <stdlib.h>
void fun (char *str)
{
}
void main()
{
char str[81];
char Msg[]="Input a string:";
int n;
FILE *out;
printf(Msg);
gets(str);
puts(str);
fun(str);
printf("*** str: %s\n",str);
/******************************/
out=fopen("out.dat","w");
fun(Msg);
fprintf(out,"%s",Msg);
fclose(out);
/******************************/
}
答案:
int i=0;
char *p=str;
while(*p)
{
if(*p!=' ') /*删除空格*/
{
str[i]=*p;
i++;
}
p++;
}
str[i]='\0'; /*加上结束符*/