1.编写函数,实现按照如下公式计算的功能。其中n为自然数。
#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);
}
2.编写函数,对给定的整数数组a(数组长度和元素个数均为N)进行判定:是否存在某个整数a[i](0<i<N),等于在其之前所有的整数的和,即a[i] = a[0] + a[1] + …+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.编写一个递归函数,计算给定正整数的所有组成数字之和
例如:给定参数为105,则返回结果应该为6(通过1+0+5=6获得)
#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个字段:姓名、性别、成绩),编写函数,将下图所示的结构体数组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 %d\n",stu[i].name,stu[i].sex,stu[i].score);
}
fclose(file);
}
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);
}