C语言程序设计第二版课后习题答案(4)
C语言程序设计第8章 指针
一、选择题
D A C C(D) D C D
二、填空题
1. m 2. 指针数组名 3. ABCDCD 4.49 5. 25
三、程序设计题
(1)main()
{
int a,b,c,*p1,*p2,*p3;
scanf("%d,%d,%d",&a,&b,&c);
p1=&a;
p2=&b;
p3=&c;
if(*p1<*p2) max=*p1 else max=*p2;
if(*p3
printf("\nmax=%d\n",max);
}
程序结果:
9,0,10<回车>
max=10
(2)#include
main()
{int a[10],*p,i,t;
p=a;
for(i=0;i<10;i++)
scanf("%d",p+i);
for(i=0;i<5;i++)
{t=*(p+i);*(p+i)=*(p+9-i);*(p+9-i)=t;}
for(i=0;i<10;i++)
printf("%5d",*(p+i));
printf("\n");
}
(3)#include
main()
{ char str[80],*p,i,len=0;
p=str;
gets(p);
for(i=0;*(p+i)!='\0';i++)
len++;
printf("len=%d\n",len);
}
项目实训题目:
#include
char *link(char *p1,int M,char *p2,int N)
{ int i,j;
for(i=0;i
if(*(p1+i)=='\0')
break;
for(j=0;j
if(*(p2+j)!='\0')
*(p1+(i++))=*(p2+j);
else
break;
*(p1+i)='\0';
return(p1);
}
main()
{
char str1[80],str2[20],*p;
gets(str1);
gets(str2);
p=link(str1,80,str2,20);
puts(p);
}
C语言程序设计第9章 结构体共同体和枚举类型
程序设计题
1.定义一个结构体变量来表示日期(包括年、月、日),并编程来计算某一日期是本年的第几天,注意考虑闰年的问题。
解:struct
{ int year;
int month;
int day;
}date;
main()
{ int days;
printf("Please input date:(year,month,day)");
scanf("%d,%d,%d",&date.year,&date.month,&date.day);
switch(date.month)
{ case 1:days=date.day; break;
case 2:days=date.day+31; break;
case 3:days=date.day+59; break;
case 4:days=date.day+90; break;
case 5:days=date.day+120; break;
case 6:days=date.day+151; break;
case 7:days=date.day+181; break;
case 8:days=date.day+212; break;
case 9:days=date.day+243; break;
case 10:days=date.day+273; break;
case 11:days=date.day+304; break;
case 12:days=date.day+334; break;
}
if((date.year%4==0&&date.year%100!=0||date.year%400==0)&&date.month>=3)
days+=1;
printf("\n%dmonth %dday is %d day of %d.",date.month,date.day,days,date.year);
}
本程序运行结果为:
Please input date:(year,month,day)2000,3,1
3month 1day is 61 day of 2000.
2、有10名学生,每个学生包括学号、姓名、3科成绩,编程序求每个学生的平均成绩,并打印最高分学生的信息。
#define N 4
main( )
{struct student
{int num;
char name[15];
float c[3];
float ave;
};
struct student stu[N];
struct student *p[N],*t;
int i,j,k; float x1,x2,x3;
for(i=0;i
{scanf("%d%s%f%f",&stu[i].num,stu[i].name,&x1,&x2,&x3);
stu[i].c[0]=x1; stu[i].c[1]=x2; stu[i].c[2]=x3;
k=0;
for(j=0;j<=2;j++)
k=k+stu[i].c[j];
stu[i].ave=k/3.0;
p[i]=&stu[i];
}
/*排序-由大到小*/
for(i=0;i
for(j=i+1;j
if(p[j]->ave
ave)
{t=p[j];p[j]=p[i];p[i]=t;}
printf(“%5d%15s%3d%3d%6.1f\n”, p[0]->num,p[i]->name, p[0]->c[0],
p[0]->c[1],p[0]->c[2]);
}
3、建立一个3名学生数据的单链表。
解:#define NULL 0
#define LEN sizeof(struct student)
struct student
{ int no;
struct student *next;
};
struct student *head;
struct student *creat()
{ struct student *p,*q;
int n,i;
printf("how many:");
scanf("%d",&n);
for(i=0;i
{ p=( struct student *)malloc(LEN);
printf("NO:"); scanf("%d",&p->no);
if(i==0) head=p;
else q->next=p;
q=p;
}
p->next=NULL;
return(head);
}
print (struct student * head )
{ struct student *p;
p=head;
while(p!=NULL)
{ printf("%6d ",p->no);
p=p->next;
}
}
main()
{ struct student * head;
head= creat();
print(head);
}
本程序运行结果为:
how many:5
NO:12
NO:78
NO:98
NO:45
NO:75
12 78 98 45 75