1.编写函数,实现按照如下公式计算的功能:其中n为自然数。
#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) | |
50 | 37 | 29 |
#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);
}