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

1.编写函数,判定正整数m和n(均至少为2)是否满足:数m为数n可分解的最小质因数(数n可分解的最小质因数为整除n的最小质数)
提示:判定m为质数且m是n的最小因数

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

bool isprime(int m,int n) {
	for(int i=0; i<m; i++) {
		if(m%i==0||n%i==0)
			return false;
	}
	if(n%m!=0)
		return false;
	return true;
}

2.编写函数,对给定的整数数组a的前n个元素排序,使得所有正整数均出现在负整数和零之前。
提示:排序结果中,正整数之间的出现顺序不受限制,负整数和0之间的出现顺序不限制。
例如:原数组为-1、4、-3、0、2、1、-9、7,则排序后可以为4、2、1、7、0、-1、-3、-9

#include <stdio.h>

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

int main() {
	int arr[]= {-1,4,-3,0,2,1,-9,7};
	sort(arr,8);
	for(int i=0; i<8; i++) {
		printf("%d ",arr[i]);
	}
}

3.编写递归函数,实现按照如下公式计算的功能。其中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);
}

double func(int n) {
	if(n==0)
		return 0;
	return 1.0*n/((n+1)*fac(n+2))+func(n-1);
}

4.定义一个表示学生的结构体(包含3个字段:姓名、性别、成绩),编写函数,将下图所示的结构体数组s中的前n个学生的信息,存储到当前目录下的output.txt中。
提示:性别可以定义为bool、int、enum等类型均可,存储信息的具体形式不限制

张三 李四 ...... 赵九
男(true) 女(false) 男(true)
83 76 97

例如:一个教师的信息为Zhangsan、true、50,另一个教师的信息为Lisi、false、37。

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

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

void save(struct student stu[],int n) {
	FILE *file;
	if((file=fopen("out.txt","w"))==NULL) {
		printf("open error");
		exit(0);
	}
	for(int i=0; i<n; i++) {
		fprintf(file,"%s %d %dn",stu[i].name,stu[i].sex,stu[i].score);
	}
	fclose(file);
}

5.定义一个单链表(每个结点包含2个字段:整数信息、后继指针),如下图所示。编写函数,删除该单链表中所含整数信息等于x的多个重复结点。
例如:若单链表中存储的整数信息依次是1、5、5、0、5、6、0、0、5、1,如果x为5,则得到的单链表中相应信息依次是1、0、6、0、0、1。

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

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

void del(struct node *head,int x) {
	struct node *dummyhead=(struct node *)malloc(sizeof(struct node));
	dummyhead->next=head;
	struct node *p=head,*pre=dummyhead;
	while(p!=NULL) {
		if(p->key==x)
			pre->next=p->next;
		else
			pre=p;
		p=p->next;
	}
}

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
在整个云计算领域,能让芯片规模化的用起来,是决定造芯是否成功的天花板。在拉斯维加斯的亚马逊云科技2023)">
< <上一篇

)">
下一篇>>