一、程序填空题
在此程序中,函数fun的功能是用函数指针指向要调用的函数,规定在【2】处使用f指向函数f1,在【3】处使用f指向函数f2。当调用正确时,程序输出:
x1=5.000000,x2=3.000000,x1*x1+x1*x2=40.000000。
#include <stdio.h>
double f1(double x)
{ return x*x; }
double f2(double x, double y)
{ return x*y; }
double fun(double a, double b)
{
/**********found**********/
__1__ (*f)();
double r1, r2;
/**********found**********/
f = __2__ ;
r1 = f(a);
/**********found**********/
f = __3__ ;
r2 = (*f)(a, b);
return r1 + r2;
}
void main()
{ double x1=5, x2=3, r;
r = fun(x1, x2);
printf("\nx1=%f, x2=%f, x1*x1+x1*x2=%f\n",x1, x2, r);
}
答案:(1) double (2) f1 (3) f2
二、程序修改题
在此程序中,建立一个带头结点的单向链表,并用随机函数为各结点赋值。函数fun的功能是将单向链表结点(不包括头结点)数据域为偶数的值累加起来,并且作为函数值返回。
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
typedef struct aa
{ int data;
struct aa *next;
} NODE;
int fun (NODE *h)
{ int sum=0;
NODE *p;
p=h->next;
/*************found**************/
while(p->next)
{ if(p->data%2==0)
sum+=p->data;
/*************found**************/
p=h->next;
}
return sum;
}
NODE *creatlink(int n)
{
NODE *h,*p,*s;
int i;
h=p=(NODE*)malloc(sizeof(NODE));
for(i=1;i<n;i++)
{
s=(NODE*)malloc(sizeof(NODE));
s->data=rand()%16;
s->next=p->next;
p->next=s;
p=p->next;
}
p->next=NULL;
return h;
}
void outlink(NODE *h)
{ NODE *p;
p=h->next;
printf("\n\n The LIST :\n\n HEAD");
while(p)
{ printf("->%d",p->data);
p=p->next;}
printf("\n");
}
void main()
{ NODE *head; int sum;
system("CLS");
head=creatlink(10);
outlink(head);
sum=fun(head);
printf("\nSUM=%d",sum);
}
答案:(1) while(p!=NULL) (2) p=p->next;
三、程序设计题
在此程序中,编写函数fun,该函数的功能是:判断字符串是否为回文,若是,则函数返回1,主函数中输出”YES”,否则返回0,主函数中输出”NO”。回文是指顺读和倒读都一样的字符串。
例如,字符串LEVEL是回文,而字符串123312就不是回文。
#include <stdio.h>
#define N 80
int fun(char *str)
{
}
void main()
{
char s[N];
FILE *out;
char *test[]={"1234321","123421","123321","abcdCBA"};
int i;
printf("Enter a string : ");
gets(s);
printf("\n\n");
puts(s);
if(fun(s))
printf("YES\n");
else
printf("NO\n");
/************************************/
out=fopen("out.dat","w");
for(i=0;i<4;i++)
if(fun(test[i]))
fprintf(out,"YES\n");
else
fprintf(out,"NO\n");
fclose(out);
/************************************/
}
答案:
int i,n=0,fg=1;
char *p=str;
while (*p) /*将指针p置位到字符串末尾,并统计字符数*/
{
n++;
p++;
}
for(i=0;i<n/2;i++) /*循环比较字符*/
if(str[i]==str[n-1-i]) ; /*相同,什么都不作*/
else /*不同,直接跳出循环*/
{
fg=0;
break;
}
return fg;