C++课后习题答案(杨志强 龚沛增) 完整版 联系客服

发布时间 : 星期二 文章C++课后习题答案(杨志强 龚沛增) 完整版更新完毕开始阅读b3173cbb960590c69ec37644

}

6. 函数convert的功能是将一个十进制整数转换为二到十六进制的字符串。 #include \

void convert(int m,int h,char ch[]) {

char b[17]=\int c[10],i=0,k=0; do

c[ ___i++__ ]=m%h; while(____(m=m/h)!=0_____); for(--i;i>=0;--i)

{ ch[k++]=b[ ___c[i]___ ]; } ______ch[k]='\\0'_______; }

void main() {

char ch[10];int m,h; cin>>m>>h; convert(m,h,ch); cout<

}

四、编写程序

1. 编写函数,功能为将字符串s中的字符c1用字符c2替换,并加以调用。函数形式为: void match(char s[], char c1,char c2); #include

void replace(char s[],char c1,char c2) {char *p=s; while(*p!='\\0') { if(*p==c1) } }

void main()

{char s[80],c1,c2; cin>>s; cin>>c1>>c2; replace(s,c1,c2); cout<

2. 编写函数,功能为求圆的周长和面积。函数分别定义为如下形式: double area(double r, double * girth ,double pi=3.14159);

*p=c2; p++;

void fun(double r, double &girth ,double &area,double pi=3.14159); 分别编二个程序实现,半径从键盘输入。 方法一、

#include

double area(double r,double *girth,double pi=3.14159) { }

*girth=2*pi*r; return(pi*r*r);

void main() {double r,len,s; cin>>r;

s=area(r,&len);

cout<<\}

方法二

#include

void fun(double r,double &girth,double &area,double pi=3.14159) {

girth=2*pi*r; area=pi*r*r; }

void main() {double r,len,s; cin>>r;

fun(r,len,s);

cout<<\}

3. 编写函数,功能是求二维数组中最大元素所在的行号和列号,再编写主函数调用之。 #define SIZE1 3 #define SIZE2 4

#include \

#include \

float max_value(float x[][4],int &ii,int &jj) {

float max=x[0][0];

for(int i=0;imax)

{max=x[i][j]; ii=i; jj=j; } return(max); }

void main()

{

int i,j,t1,t2;float a[SIZE1][SIZE2]; cout<<\for(i=0;i

cout<<\cout<<\

}

4. 编写函数,将两个字符串s和t的前n个字符拼接成新的字符串,结果存放在s中。如果s或t中字符串的长度不足n,按实际长度处理。例如,如果有\和\为3,则新的字符串为”ABCabc”,并加以调用。函数形式为: void mystrcat(char s[],char t[],int n); #include #include

void mystrcat(char s[],char t[],int n) { }

int l1=strlen(s),l2=strlen(t); int k1=l1>n?n:l1,k2=l2>n?n:l2; for(int i=0;i

void main() { char s[30],t[30];

int n;

cin>>s>>t; cin>>n;

mystrcat(s,t,n);

cout<

5. 编写函数,其功能是逐字符比较两个字符串s1和s2,并将s1中第一个与s2不相同字符的地址返回给主函数。再编写主函数调用该函数,并在主函数中输出s1从这个位置开始的子串。函数形式为: char *dif(char s1[],char s2[]); #include #include \

char *dif(char s1[],char s2[]) {

}

int i=0;

while(s1[i]==s2[i]&&s1[i]!='\\0') i++; if(s1[i]!='\\0') return(&s1[i]); else return NULL;

void main() {

char s[30],t[30]; cin>>s>>t; char *p;

if((p=dif(s,t))!=NULL) cout<

else cout<<\包含于t中\\n\

}

6. 用递归方法求正整数m,n的最大公约数。 #include int gcd(int m,int n) { }

int r=m%n; if(r!=0) return gcd(n,r); else

return(n);

void main() { int m,n;

cin>>m>>n;

cout<

}

7. 编写四个同名函数max,分别求两个整数、三个整数,两个双精度数、三个双精度数的最大值。

#include int max(int a,int b) { }

int max(int a,int b,int c) {

int t=max(a,b); return(max(t,c)); return(a>b?a:b);