當前位置:成語大全網 - 新華字典 - C++新手指針習題

C++新手指針習題

三、填空題

1. 下列函數change的功能是,將字符串中的小寫字母轉成大寫字母,請填空。

#include<iostream>

void change( ) //1

{int i=0;

for(i=0; ;i++) //2

if(a[i]>='a'&&a[i]<='z')

; //3

}

int main()

{ char p[80];

cout<<" \n";

cin.getline(p,80) ; //讀壹行字符,中間可以有空格

change(p);

cout<<p<<endl;

}

如程序運行時得到以下結果:

請輸入壹行字符:

This is a book..

THIS IS A BOOK.

答案:(1)char *a 或 char a[80]

(2) a[i] 或 a[i]!=’\0’

(3) a[i]= a[i] –32或a[i]-= a[i]

2. 下列函數swap實現數據交換功能功能,請填空。

#include<iostream>

void swap(int *p,int *q)

{ int temp;

temp=*p;

; //1

; //2

}

int main()

{ int a,b;

int *p1,*p2;

cout<<"請輸入兩個正數:";

cin>>a>>b;

p1=&a;

p2=&b;

swap(p1,p2);

cout<<"結果a和b的值:"<<a<<","<<b<<endl;

}

如程序運行時得到以下結果:

請輸入兩個正數:10 20

結果a和b的值:20,10

答案:

(1) *p=*q

(2) *q=temp;

3. 下列函數sort實現對字符串按字典順序由小到大排序,請填空。

#include<iostream>

void sort( ) //1

{ char ; //2

int i,j;

for(i=0;i<n-1;i++)

for(j=0;j<n-1-i;j++)

if(strcmp( ) //3

{ temp=p[j];

; //4

p[j+1]=temp;

}

}

int main()

{

char *a[5]={"student","worker","cadre","soldier","apen"};

sort(a,5);

for(int i=0;i<5;i++)

cout<<a[i]<<endl;

}

程序運行結果如下:

apen

cadre

soldier

student

worker

答案:(1)char *p[],int n

(2)*temp

(3)p[j],p[j+1])>0

(4)p[j]=p[j+1]

4.函數find功能是:在指針p所指數組中,查找值為x的元素,找到後,返回該元素的下標,否則返回-1,改正程序中語句錯誤,能夠正確運行。

#include<iostream>

#include<stdlib.h>

const int N=10;

int find(int *p,int n,int x) //1

{ int i ; // 2

*(p+n)=x; //3

while(*p+i!=x) //4

i++; //5

if(i!=n) //6

return 1; //7

else

return -1; //8

}

int main()

{ int i,pos,x;

int *p=new int [N];

for(i=0;i<N;i++)

*(p+i)=rand()%50;

for(i=0;i<N;i++)

cout<<*(p+i)<<'\t';

cout<<"\ninput x: ";

cin>>x;

pos=find(p,N,x);

if(pos!=-1)cout<<"index= "<<pos<<" ,value= "<<*(p+pos)<<endl;

else cout<<"No find!"<<endl;

}

答案:(1) 2行語句改為 int i=0;

(2) 4行語句改為 while(*(p+i)!=x);

(3) 7行語句改為 return i 。

四、編程題

1. 寫壹個函數,將壹個n階方陣轉置。具體要求如下:

(1)初始化壹個矩陣A(5×5),元素值取自隨機函數,並輸出。

(2)將其傳遞給函數,實現矩陣轉置。

(3) 在主函數中輸出轉置後的矩陣。(提示:程序中可以使用C++庫函數rand( ),其功能是產生壹個隨機數0~65535,其頭文件為stdlib.h)

2.使用指針編寫函數strcat(),實現兩個字符串的首尾連接(將字符串str2接到str1的後面,str1最後面的‘\0’被取消)。

3.編寫從多個字符串中尋找最長串的函數

4.編寫壹個程序,實現在命令行中以參數的形式接收兩個整數,輸出這兩個整數的和。(提示:程序中可以使用C++庫函數atoi(),其功能是將字符串轉換成整型值,其頭文件為stdlib.h)