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

本文介绍了C语言中实现的五个功能:递归计算整数和、阶乘函数、判断数组元素特性、教师信息结构体及链表操作,展示了基础编程中的数学和数据管理技术。
摘要由CSDN通过智能技术生成

1.编写函数,实现按照如下公式计算的功能:其中n为自然数。

f(n)=0/(1*2!)+1/(2*3!)+2/(3*4!)+...+n/((n+1)*(n+2)!)

#include <stdio.h>

int fac(int n) {
	if(n==0)
		return 1;
	else
		return n*fac(n-1);
}

float fun(int n) {
	float flag;
	float sum=0;
	for(int i=0; i<=n; i++) {
		flag=i/((i+1)*fac(i+2));
		sum+=flag;
	}
	return sum;
}

2.编写bool函数,判断给定的整数数组a[n]中是否存在元素a[i],i的取值范围为0到n,等于其前边所有元素之和,即a[i]=a[0]+a[1]+a[2]+a[3]+…a[i-1]

#include <stdio.h>
#include <stdbool.h>

bool judge(int *a,int n) {
	for(int i=0; i<n; i++) {
		int sum=0;
		for(int j=0; j<i; j++)
			sum+=a[j];
		if(sum==a[i])
			return true;
	}
	return false;
}

int main() {
	int a[]= {2,21,1,4,5};
	printf("%d",judge(a,5));
}

3.编写一个递归函数,计算组成给定正整数n的所有数字之和。
例如:给定参数为1035,则返回结果应该为9(通过1+0+3+5=9获得)

#include <stdio.h>

int func(int n) {
	int sum=0;
	while(n>0) {
		sum+=n%10;
		n/=10;
	}
	return sum;
}

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

4.构造一个表示教师的结构体(包含3个字段:姓名、性别、年龄)。编写函数,读入M个教师的信息,存入一个结构图数组中,如下图所示。

例如:一个教师的信息位张三、true、50,另一个教师的信息位李四、false、37,

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

typedef struct teacher {
	char name[20];
	bool sex;
	int age;
	struct teacher *next;
} teacher;

struct teacher* create() {
	struct teacher *p,*p0,*head=NULL;
	p0=(struct teacher *)malloc(sizeof(struct teacher));
	p0->next=NULL;
	head=p0;
	for(int i=0; i<n; i++) {
		p=(struct teacher *)malloc(sizeof(struct teacher));
		printf("NO.%d",i);
		scanf("%s%d%d",p->name,p->sex,p->age);
		p0->next=p;
		p->next=NULL;
		p0=p0->next;
	}
	p=head;
	head=head->next;
	free(p);
	return head;
}

5.设有一个保存教师信息的单链表,(每个结点包含四个字段:姓名,性别,年龄,后继指针),构造该链表中一节的数据类型声明:编写函数,在给定链表上查找所有女教师的信息,并存储到指定文件output.txt中。

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

typedef struct teacher {
	char name[20];
	bool sex;
	int age;
	struct teacher *next;
} teacher;

void write(struct teacher *head) {
	FILE *file;
	if((file=fopen("output.txt","w"))==NULL)
		printf("open error");
	while(head!=NULL) {
		if(head->sex=false)
			fprintf(file,"%10s %d",head->name,head->age);
		head=head->next;
	}
	fclose(file);
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值