高级语言期末2014级B卷(软件学院)

1.编写函数,删除整形数组中所有为0的元素,将处理后的数组输出,并返回剩余元素个数。
注意:函数中不能定义额外的新数组。

#include <stdio.h>

int delarr(int a[],int n) {
	for(int i=0; i<n; i++)
		if(a[i]==0) {
			for(int j=i; j<n-1; j++)
				a[j]=a[j+1];
			i--;
			n--;
		}
	for(int i=0; i<n; i++)
		printf("%d ",a[i]);
}

2.编写函数,对一个给定字符串中的所有字符(不考虑默认字符串结束符’\0’)进行排序,使得排序后的字符串满足从左到右为ASCLL码递增的字符序列。
注:本题中不准使用string.h头文件和相关的字符串处理函数,以及系统定义的各类排序函数。

#include <stdio.h>

void sort(char *str,int n) {
	for(int i=0; i<n-1; i++)
		for(int j=0; j<n-1-i; j++) 
			if(str[j]>str[j+1]) {
				char temp = str[j];
				str[j] = str[j + 1];
				str[j + 1] = temp;
			}
}

int main() {
	char str[] = "lajfbaiubgcaiuncoadd";
	sort(str, 20);
	printf("%s", str);
	return 0;
}

3.编写递归函数,计算给定数组中所有元素的中位数,中位数标准定义为:按照从小到大排序后正中间的数。如果元素个数为偶数,取最中间的两个数的平均数作为中位数。本题可以粗略地认为n个元素的中位数为按照从小到大排序后的第n/2个数。

#include <stdio.h>

int func(int *a,int n,int k) {
	int min=0;
	for(int j=0; j<n; j++) {
		if(a[j]<a[min])
			min=j;
	}
	int temp=a[0];
	a[0]=a[min];
	a[min]=temp;
	if(k==1) {
		return a[0];
	}
	func(a+1,n-1,k-1);
}

int main() {
	int a[] = {9, 5, 1, 2, 7, 3};
	int n = sizeof(a) / sizeof(a[0]);
	if(n%2==0)
		printf("%.1f",(func(a, n, n/2)+func(a, n, n/2+1))/2.0);
	else
		printf("%d",func(a, n, n/2+1));
	return 0;
}

4.每个教师的信息卡片包括教工号、姓名、性别、入职年份(限定为1900-2100之间的整数)四项。定义存储教师信息的单向链表的结点类型;编写函数,由当前目录下文件名为:input.txt的文件依次读入n个教师的信息,创建一个用于管理信息的单向链表。

#include <stdio.h>
#include <stdlib.h>

typedef struct teacher {
	int id;
	char name[20];
	int sex;
	int year;
	struct teacher *next;
} teacher;

struct teacher *create(int n) {
	FILE *file;
	if((file=fopen("input.txt","r"))==NULL) {
		printf("open error");
		exit(0);
	}
	struct teacher *head,*p1,*p2;
	p1=(struct teacher *)malloc(sizeof(struct teacher));
	fscanf(file,"%d%s%d%d\n",&p1->id,&p1->name,&p1->sex,&p1->year);
	head=p1;
	p2=p1;
	int m=1;
	while(m<n) {
		p1=(struct teacher *)malloc(sizeof(struct teacher));
		fscanf(file,"%d%s%d%d\n",&p1->id,&p1->name,&p1->sex,&p1->year);
		p2->next=p1;
		p2=p1;
		m++;
	}
	p2->next=NULL;
	fclose(file);
	return head;
}

5.编写函数,在上题创建的单向链表中删除所有入职年份大于k(k的值由用户从键盘输入,且限定为1900-2100之间的整数)的结点。

#include <stdio.h>
#include <stdlib.h>

typedef struct teacher {
	int id;
	char name[20];
	int sex;
	int year;
	struct teacher *next;
} teacher;

struct teacher *del(struct teacher *head) {
	int k;
	scanf("%d",&k);
	while(k<1900&&k>2100) {
		printf("error,must in 1900-2100");
		scanf("%d",&k);
	}
	while(head!=NULL&&head->year>k) {
		head=head->next;
		struct teacher *p=head,*q=NULL;
		while(p!=NULL) {
			if(head->year<=k)
				q=p;
			else
				q->next=p->next;
			p=p->next;
		}
		return head;
	}
}
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值