for(i=0;i<=n;i++) /*分别输出各序号、字符串*/ {
printf(\ puts(str[k[i]]); } }
getch(); }
28.已知数组 a 中有 m 个按升序排列的元素,数组 b 中有 n 个按降序排列的元素,编程将 a 与 b 中的所有元素按降序存入数组 c 中。
【提示】将 a 中的元素最大值与 b 中元素最大值相比,将最大值存入 c 数组中,然后调整 c 、a 或 b 元素指针(地址),依次重复前序工作,即可。 #define M 3 #define N 7 main()
{
int i=0,j=0,n=0,c[M+N],a[3]={10,27,543},b[7]={300,210,173,96,55,34,13}; int maxa,maxb; do {
maxa=a[M-i-1];maxb=b[j]; if(maxa>maxb)
{
c[n++]=maxa; /*将 a 中最大元素赋值给 c 数组当前元素,并调整 c 新元素位置*/
i++; /*调整 a 中元素位置*/ } else {
c[n++]=maxb; /*将 a 中最大元素赋值给 c 数组当前元素,并调整 c 新元素位置*/
j++; /*调整 b 中元素位置*/ }
printf(\打印输出 c 中新赋值元素数据*/
}while(n 第八章 1.指针变量初始化。 #include { int a=18,*p=&a; printf(“a=%d\\n”,a); printf(“*p=%d\\n”,*p); } 2.从键盘输入两个整数到a、b,按由大到小输出。 #include { int a,b,*pa=&a,*pb=&b,*p; scanf(“%d %d”,&a,&b); if(*pa<*pb) { p=pa; pa=pb; pb=p; } printf(“\\na=%d,b=%d\\n”,a,b); printf(“\\n max=%d,min=%d”,*pa,*pb); } 3.二级指针的使用。 #include { int a=22,*p,**pp; p=&a; pp=&p; printf(“*p=%d\\n”,*p); printf(“**pp=%d\\n”,**pp); } 4.编写一个交换两个变量的函数,在主程序中调用,实现两个变量值的交换。 #include int *pa,*pb; void swap(int *p1,int *p2); scanf(“%d%d”,&a,&b); pa=&a; pb=&b; swap(pa,pb); printf(“\\na=%d,b=%d\\n”,a,b); } void swap(int *p1,int *p2) {int temp; temp=*p1; *p1=*p2; *p2=temp; } 5.指针交换比较。 #include { int a,b,*pa,*pb; void swap(int *p1,int *p2) pa=&a; pb=&b; scanf(“%d %d”,&a,&b); swap(pa,pb); printf(“\\n main0:a=%d,b=%d\\n”,a,b); printf(“\\n main1:*pa=%d,*pb=%d\\n”,*pa,*pb); } void swap(int *p1,*p2) { int *p; p=p1; p1=p2; p2=p; printf(“\\nswap:*p1=%d,*p2=%d\\n”,*p1,*p2); } 6.指针函数实例。 #include int *min(int x,int y); int *minp(int *,int *); scanf(“\\nmin=%d”,*p); p=min(a,b); printf(“\\nmin=%d”,*p); p=minp(&a,&b); printf(“\\nminp=%d”,*p); } int *min(int x,int y) { if(x int *minp(int *x,int *y) { int *q; q=*x<*y?x:y; return(q); } 7.函数max()用来求一维数组中元素的最大值,在主调函数中用函数名调用该函数与函数指针调用该函数来实现。 #include #define M 8 void main() { float sumf,sump; float a[M]={11,2,-3,4,5,5,69,7,80}; float(*p)() float max(float a[],int n); p=max; sump=(*p)(a,M); sumf=max(a,M); printf(“sump=%.2f\\n”,sump); printf(“sumf=%.2f\\n”,sumf); } float max(float a[],int n) { int k; float s; s=a[0]; for(k=0;k } 8.在主函数中输入三角形的两条直角边,求三角形的面积和斜边长。 #include int m,n; float s,l; float(*q)(); float area(int a,int b,float(*p)(); scanf(“%d%d”,&m,&n); q=area; s=f(m,n,q); l=f(m,n,length); printf(“Area of the right triangle is %.2f\\n”,s); printf(“Length of the hypotenuse is %.2f\\n”,l); } float area(int a,int b) {float z; z=a*b/2; return(z); } float z; z=sqrt(a*a+b*b); return(z);
相关推荐: