一、堂上限时练习
1、[填空]交换两数,由大到小输出。
下面程序,交换两数,使两数由大到小输出,请填空。
#include "stdio.h"
void swap(_______________________)
{
int temp;
temp=*p1;
*p1=*p2;
*p2=temp;
}
int main()
{ int a,b; int *pa,*pb;
scanf("%d%d", &a, &b);
pa=&a; pb=&b;
if(a<b) swap(_______________________);
printf("%d %d\n",a,b);
}
输入样例
1 2
输出样例
2 1
*注意:p1 表示指向地址p1的值,p1是指针变量,专门表示地址
答案:
#include "stdio.h"
void swap(int *p1,int *p2)
{
int temp;
temp=*p1;//*pa,*pb表示值
*p1=*p2;
*p2=temp;
}
int main()
{ int a,b; int *pa,*pb;
scanf("%d%d", &a, &b);
pa=&a; pb=&b;//pa,pb表示地址
if(a<b) swap(pa,pb);
printf("%d %d\n",a,b);
}
2、[填空]函数实现求字符串长度。
下面程序实现由函数实现求字符串长度,再填空完成
#include "stdio.h"
/*create function f*/
_______________________
int main()
{
char s[80];
int i;
scanf("%s", s);
i=f(s);
printf("%d", i);
}
输入样例
Hello!
输出样例
6
答案:
#include "stdio.h"
#include<string.h>
/*create function f*/
int f(char a[])//把实参的s[]的值赋给形参a[],具体长度根据s[]来定
{
char *p;//定义一个指针变量
p=a;//a[0]的地址赋值给p指针
while(*p!='\0')//*p代表p指向的值
{
p++;//指针P向后移动
}
return p-a;//p的地址数-a[0]的地址
}
int main()
{
char s[80];
int i;
scanf("%s", s);
i=f(s);
printf("%d", i);
}
4、定义结构体类型
要求定义一个名为student的结构体类型,其包含如下成员:
(1)字符数组name,最多可存放10个字符;
(2)字符变量sex,用于记录性别;
(3)整数类型变量num,用于记录学号;
(4)float类型变量score,用于记录成绩;
并使下列代码完整。
#include "stdio.h"
_______________________
int main()
{
struct student stu;
gets(stu.name);
scanf("%c", &stu.sex);
scanf("%d", &stu.num);
scanf("%f", &stu.score);
printf("%s\n", stu.name);
printf("%c\n", stu.sex);
printf("%d\n", stu.num);
printf("%f\n", stu.score);
return 0;
}
答案:
#include "stdio.h"
struct student
{
char name[10];
char sex;
int num;
float score;
};//记得分号不要掉
int main()
{
struct student stu;
gets(stu.name);
scanf("%c", &stu.sex);
scanf("%d", &stu.num);
scanf("%f", &stu.score);
printf("%s\n", stu.name);
printf("%c\n", stu.sex);
printf("%d\n", stu.num);
printf("%f\n", stu.score);
return 0;
}