高级语言期末2012级A卷(软件学院)

本文介绍了C语言中的五个编程示例,包括计算整数位数、去重整型数组、递归求最大公约数、读取并筛选男学生信息以及删除链表中奇数节点。
摘要由CSDN通过智能技术生成

1.编写函数,输出任意正整数n的位数(n默认为存储十进制的整形变量)
例如:正整数13,则输出2,;正整数3088,则输出4

#include <stdio.h>
 
int func(int n) {
	int count=0;
	while(n>0) {
		n/=10;
		count++;
	}
	return count;
}

int main() {
	printf("%d",func(21222));
}

2.编写函数,对给定有序整形数组进行整理,使得所有整数只保留一次出现。
例如:原数组为-2、-2、-1、0、0、1、4、4、4,则处理后的结果为-2、-1、0、1、4

#include <stdio.h>

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

3.编写递归函数,求两个数x和y的最大公约数。公式递归定义如下:

gcd(x,y)=\left\{\begin{matrix} x,y=0 & \\ gcd(y,x\%y),y!=0 & \end{matrix}\right.

#include <stdio.h>

int gcd(int x,int y) {
	if(y==0)
		return x;
	else
		return gcd(y,x%y);
}

4.给定图1所示的存储学生信息的结构体数组(每个结构体包含3个字段:姓名、性别、成绩),编写函数,将指定文件in.txt中所有男学生信息存储到该结构体数组中。
(假定文件中存储信息与结构体信息格式相应)

张三李四......赵九
男(true)女(false)男(true)
837697
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

typedef struct student {
	char name[20];
	bool sex;
	int score;
} student;

int save(struct student stu[]) {
	FILE *file;
	if((file=fopen("out.txt","w"))==NULL) {
		printf("open error");
		exit(0);
	}
	int i=0;
	while(!feof(file)) {
		fscanf(file,"%s",&stu[i].name);
		fscanf(file,"%d",&stu[i].sex);
		fscanf(file,"%d",&stu[i].score);
		fscanf(file,"\n");
		if(stu[i].sex)
			i++;
	}
	fclose(file);
	return i;
}

5.给定图2所示的单链表,(每个结点包含2个字段:整数信息、后继指针),编写函数删除该单链表中整数信息为奇数的结点。
例如:若单链表中存储的整数信息依次为1、5、6、3、6、0、0、5、2、1,则处理后的链表中存储的key值依次为6、6、0、0、2。

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

typedef struct node {
	int key;
	struct node *next;
} node;

struct node *del(struct node *head) {
	if(head==NULL)
		return head;
	while(head!=NULL&&head->key%2==1)
		head=head->next;
	struct node* q=head,*p=head->next;
	while(p!=NULL) {
		if(p->key%2==1)
			q->next=p->next;
		else
			q=p;
		p=p->next;
	}
	return head;
}
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值