1.编写函数,实现按照如下公式计算的功能,其中n为自然数且n>=0,0!=1。
#include <stdio.h>
#include <math.h>
int fac(int n) {
if(n==0)
return 1;
else
return n*fac(n-1);
}
float func(int n) {
float flag;
float sum=0;
for(int i=0; i<=n; i++) {
flag=fac(i)/pow(2,i);
sum+=flag;
}
return sum;
}
2.编写递归函数,输出一个正整数的所有质因数(质因数分解中得到的重复质因子需要多次输出)。
例如:1没有质因数;2的质因数为2;18的质因数为2、3和3;48的质因数为2、2、2、2和3。
#include <stdio.h>
void func(int n) {
if(n==1)
return;
for(int i=2; i<=n; i++)
if(n%i==0) {
printf("%d ",i);
func(n/i);
return;
}
}
3.定义存储学生信息的结构体至少应包含:学号、姓名、成绩、指向下一个结构体的指针4个字段。编写函数,将图1所示的链表中成绩不及格(0-59分)的学生人数和不及格学生的全部信息存储到指定文件class531316.txt中。
#include <stdio.h>
#include <stdlib.h>
typedef struct student {
int num;
char name[20];
int score;
struct student *next;
} student;
void save(struct student* head) {
FILE *file;
if((file=fopen("class531316.txt","w"))==NULL) {
printf("open error");
exit(0);
}
struct student *p=head;
int count=0;
while(p!=NULL) {
if(p->score>=0&&p->score<=59) {
fprintf(file,"%d %s %d\n",p->num,p->name,p->score);
count++;
}
p=p->next;
}
fprintf(file,"not pass people is %d",count);
fclose(file);
}
4.给定图2所示的链表,每个结点包含:整数信息key和后继指针next。编写函数,对该链表进行排序,使得处理后的链表保持非降序。
例如:若链表中存储的key值依次为1、0、3、3、0、7、9、1,则处理后的链表中存储的key值依次为0、0、1、1、3、3、7、9。
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int key;
struct node *next;
} node;
struct node * sort(struct node *head) {
struct node *dummyhead=(struct node *)malloc(sizeof(struct node));
dummyhead->next=NULL;
struct node *pre=dummyhead,*p=head;
while(p!=NULL) {
struct node* temp=p->next;
while(pre->next!=NULL&&pre->next->key<p->key)
pre=pre->next;
p->next=pre->next;
pre->next=p;
pre=dummyhead;
p=temp;
}
return dummyhead->next;
}