一、程序填空题
此程序描述的是:围绕山顶一圈有N个山洞,编号为0、1、2、3、……、N-1,有一只狐狸和一只兔子在洞中居住。狐狸总想找到兔子并吃掉它,它的寻找方法是先到第一个洞(编号为0的洞)中找;再隔1个洞,即到编号为2的个洞中找;再隔2个洞,即到编号为5的洞中找;下次再3个洞;即到编号为9的洞中找;……。若狐狸找一圈,请为兔子指出所有不安全的洞号。程序中用a数组元素模拟一个洞,数组元素的下标即为洞号,数组元素中的值为0时,表示该洞安全,为1时表示该洞不安全。若形参n的值为30时,不安全的洞号是0、2、5、9、14、20、27。
#include <stdio.h>
#define N 100
void fun( int *a , int n )
{ int i, t;
for( i=0; i<n; i++ )
/**********found**********/
a[i]=___1___;
i=0;
/**********found**********/
___2___=1;
while( i<n )
{ a[i]= 1;
t++;
/**********found**********/
i=___3___;
}
}
void main()
{ int a[N], i, n=30;
fun( a, n);
for(i=0; i<n; i++)
if( a[i]==1 ) printf("不安全的洞号是 : %d\n",i );
}
答案:(1) 0 (2) t (3) i+t
二、程序修改题
在此程序中,规定输入的字符串全部为字母,fun函数的功能是:统计a所指字符串中每个字母在字符串中出现的次数(统计时不区分大小写),并将出现次数最高的字母输出(如果有多个相同,输出一个即可)。
例如,对于字符串:dadbcdbabdb,对应的输出应为:b或d。
#include<stdio.h>
#include <stdio.h>
#include <string.h>
void fun(char a[])
{ int b[26], i, n,max;
for (i=0; i<26; i++)
/**********found**********/
a[i] = 0;
n= strlen(a);
for (i=0; i<n; i++)
if (a[i] >='a' && a[i]<='z')
/**********found**********/
b[a[i] - 'A']++;
else if (a[i] >='A' && a[i]<='Z')
b[a[i] -'A']++;
max = 0;
for (i=1; i<26; i++)
/**********found**********/
if (b[max] > b[i])
max=i;
printf("出现次数最多的字符是 : %c\n", max + 'a');
}
void main( )
{ char a[200];
printf("请输入一个待统计的字符串 : "); scanf("%s", a);
fun(a);
}
答案:(1) b[i] = 0; (2) b[a[i] - 'a']++; (3) if (b[max] < b[i])
三、程序设计题
在此程序中,编写函数fun,其功能是将一个数字字符串转换成与其面值相同的长整型整数。可调用strlen函数求字符串的长度。
例如:在键盘输入字符串2345210,函数返回长整型数2345210。
#include <stdio.h>
#include <string.h>
void NONO();
long fun( char *s )
{
}
void main()
{ char s[10]; long r;
printf("请输入一个长度不超过9个字符的数字字符串 : "); gets(s);
r = fun( s );
printf(" r = %ld\n" , r );
NONO();
}
void NONO()
{/* 本函数用于打开文件,输入数据,调用函数,输出数据,关闭文件。 */
FILE *fp, *wf ;
int i; long r;
char s[10], *p;
fp = fopen("in.dat","r") ;
wf = fopen("out.dat","w") ;
for(i = 0 ; i < 10 ; i++) {
fgets(s, 10, fp);
p = strchr(s, '\n');
if (p) *p = 0;
r = fun(s);
fprintf(wf, "%ld\n", r);
}
fclose(fp) ;
fclose(wf) ;
}
答案:
int i,sum=0,len;
len=strlen(s);
for(i=0;i<len;i++)
{
sum=sum*10+*s-48;
s++;
}
return sum;