一、程式填空題
請補充函式proc(char*str),該函式的功能是把字串中的內容逆置。
例如,字串中原有的字串為abcdef9,則呼叫該函式後,串中的內容變為gfedcba。
注意:部分源程式給出如下。
請勿改動main()函式和其他函式中的任何內容,僅在函式proc()的橫線上填入所編寫的.若干表示式或語句。
試題程式:
#include
#include t
#include
#include
#define M 81
void proc(char*str)
【2】 ;
【3】 ;
}
}
void main()
{
char str[M];
system("CLS"):
printf("Enter a string:");
gets(str);
printf("The original string is:");
puts(str);
proc(str);
printf("n");
printf("The string after modified:");
puts(str);
}
二、程式改錯題
下列給定程式中,函式proc()的功能是:將字串str 中所有字元複製到字串b中,要求每複製3個字元之後插入一個空格。例如,在呼叫proc()函式之前給字串str 輸入abcdefghijk,呼叫函式之後,字串b中的內容則為abe def ghijk。
請修改程式中的錯誤,使它能得出正確的結果。
注意:不要改動main()函式,不得增行或刪行,也不得更改程式的結構。
試題程式:
#include
void proc(char*str,char*b)
{
int i,k=0:
while(*str)
//****found****
{
i=1;
//****found****
while(i<3||*str)
{
b[k]=*str;
k++;str++;i++;
}
if(*str)
//****found****
{b[k]=’’;}
void main()
{
char str[80],b[80];
printf("Enter a string:");gets(str);
printf("The original string:");
puts(str);
proc(str,b);
printf("nThe string after insert
space:");puts(b);printf("nn");
}
三、程式設計題
請編寫函式proc(),該函式的功能是:移動一維陣列中的內容,若陣列中有n個整數,要求把下標從P到n-1(p≤n-1)的陣列元素平移到陣列的前面。
例如,一維陣列中的原始內容為1,2,3,4,5,6,7,8,9,10,11,12,13,14,p的值為4。移動後,一維陣列中的內容應為5,6,7,8,9,10,11,12,13,14,1,2,3,4。
注意:部分源程式給出如下。
請勿改動main()函式和其他函式中的任何內容,僅在函式proc()的花括號中填入所編寫的若干語句。
試題程式:
#include
#define M 80
void proc(int * w,int P,int n)
{
}
void main()
{
int arr[M]={1,2,3,4,5,6,7,8,9,10,11,12,13,14};
int i,p,n=14;
printf("The original data:n");
for(i=0:i
printf("%3d",arr[i]);
printf("nnEnter P:");
scanf("%d",&p);
proc(arr,p,n);
printf("nThe data after moving:n");
for(i=0:i
printf("%3d",arr[i]);
printf("nn");
}
【參考答案】
一、程式填空題
【1】i
【解析】要將字串中的內容逆置.可以通過將字串中的第一個字元和最後一個字元互換,第二個和倒數第二個互換,直到字串str最中間的字元為止,因此,【1】處填“i
二、程式改錯題
(1)錯誤:i=1:
正確:i=0;
(2)錯誤:while(i<3||*str)
正確:while(i<3&&*str)
(3)錯誤:b[k]=’’;
正確:b[k++]=’’;
【解析】由函式proc()可知,變數i為計算每次字元個數是否到3的計數器變數,其初始值為0,因此,i=1;應改為i =0;。當計數器i小於3,而且字串str沒有結束時,將str 中的字元賦值給字串b,因此,“while(i<3||*str)”應改為“while(i<3&&*str)”。每次計數器變數為3而字串str沒有結束時,為字串b賦值為空格,而不是空字元,因此,“b[k]=’’;”應改為“b[k++]=’’;”。
三、程式設計題
void proc(int*w,int p,int n)
{
int i,j,t;
for(i=P;i<=n-1;i++)
{ t=w[n-1];//t放最後一個元素
for(j=n-2;j>=0;j--)
w[j+1]=w[j]; //每迴圈一次,把所有的元
素往後侈
w[0]=t; //再把最後一個放到第一個空間中
}
}
【解析】題目中要求把下標從p到n-1的陣列元素平移到陣列的前面,可以通過每一次迴圈將最後一個元素放在第一個位置上,使其成為第一個元素,其餘元素後移一個位置。通過n-1-p次迴圈實現將從p到n-1的陣列元素平移到陣列的前面。