1.填空题
请补充函数fun(),该函数的功能是:把从主函数中输入的字符串str2接在字符串str1的后面。
例如:str1=“How do”,str2=“ you do?”,结果输出:How do you do?
注意:部分源程序给出如下。
请勿改动主函数main和其他函数中的任何内容,仅在函数fun的横线上填入所编写的若干表达式或语句。
试题程序:
#include
#include
#define N 40
void fun(char *str1,char *str2)
{
int i=0;
char *p1=str1;
char *p2=str2;
while(【1】)
i++;
for( ;【2】;i++)
*(p1+i)=【3】;
*(p1+i)='\0';
}
main()
{
char str1[N],str2[N];
clrscr();
printf("*****Input the string str1 &
str2*****\n");
printf(" \nstr1:");
gets(str1);
printf(" \nstr2:");
gets(str2);
printf("**The string str1 & str2**\n");
puts(str1);
puts(str2);
fun(str1,str2);
printf("*****The new string *****\n");
puts(str1);
}
答案及评析:
【1】*(p1+i) 【2】*p2 【3】*p2++
【解析】填空1:变量i用来记录字符串str1的长度,当指针指到字符串str1结束标志符‘\0'时,while循环结束,变量i停止累加。填空2:指针p2指向字符串str2,通过for循环将字符串str2接在str1后面,循环结束的条件是指针p2所指的字符是字符串结束标志符‘\0'。填空3:指针p2最初指向字符串str2的首字符,通过自加1,使指针p2依次向后移动,指向str2的各个字符,实现将字符串str2接在str1后面的功能。 [NextPage]
[NextPage]
3. 编程题
请编写函数fun(),该函数的功能是:移动一维数组中的内容,若数组中有n个整数,要求把下标从p到n-1(p≤n-1)的数组元素平移到数组的前面。
例如,一维数组中的原始内容为1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,p的值为6。移动后,一维数组中的内容应为7,8,9,10,10,11,12,13,14,15,1,2,3,4,5,6。
注意:部分源程序给出如下。
请勿改动主函数main和其他函数中的任何内容,仅在函数fun的花括号中填入所编写的若干语句。
试题程序:
#include
#define N 80
void fun(int *w, int p, int n)
{
}
main()
{
int a[N]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
int i, p, n=15;
printf("The original data:\n");
for(i=0;i printf("=",a[i]); printf("\n\nEnter p: "); scanf("%d",&p); fun(a,p,n); printf("\nThe data after moving:\n"); for(i=0;i printf("=",a[i]); printf("\n\n"); } 答案及评析: void fun(int *w, int p, int n) { int i,j,t; for(i=p;i<=n-1;i++) /*循环右移n-p次*/ {t=w[n-1]; for(j=n-2;j>=0;j--) /*实现循环右移*/ w[j+1]=w[j]; w[0]=t; } } 【解析】本题采用"循环右移"的算法。和我们在前面分析的稍有不同的是,一个是整型数组,一个是字符型数组。
| 广告合作:400-664-0084 全国热线:400-664-0084 Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号 珠峰网 版权所有 All Rights Reserved
|