1.编写递归函数float comp(float a[][2], int n),计算两个给定n维向量u,v的内积。a的每行为一个向量,函数值为计算出的内积。
#include <stdio.h>
float comp(float a[][2],int n) {
if(n==0)
return 0;
return comp(a,n-1)+a[n-1][0]*a[n-1][1];
}
2.编写函数int changestr(char *s),把给定字符串s修改为回文字字符串。修改方法是:以左半段为基本字符串,把右半段修改成左半段的反序(不考虑结尾字符串结束符’\n’)。函数值带回结果字符串长度。设对应s的实在参数是一个字符串。
例:字符串“aba”,“a a”和“abcacba”均为回文字,而“ab”不是回文字
注:本题不允许使用string.h头文件和相关的字符串处理函数,不允许再声明其他数组。
#include <stdio.h>
int changestr(char *s) {
int num=0;
while(s[num]!='\0')
num++;
int last=num-1;
while(last>=0) {
s[num]=s[last];
num++;
last--;
}
s[num]='\0';
return num;
}
3.编写函数int delarr(int a[][10], int n),删除n行10列两维正整型数组a中所有素数,要求:
1)a数组中剩余元素保持原来次序
2)将处理后的数组最后一个有效元素位置的行、列号删除
3)函数值返回剩余元素个数
4)不能定义额外的新数组
#include <stdio.h>
int delarr(int a[][10], int n) {
int k = -1;
for(int i = 0; i < n; i++)
for(int j = 0; j < 10; j++)
if(!isPrime(a[i][j]))
k++;
a[k / 10][k % 10] = a[i][j];
printf("%d %d\n",k / 10,k % 10 - 1);
return k;
}
int prime(int n) {
if(n==1)
return 0;
for(int i=2; i<=n/2; i++)
if(n%2==0)
return 0;
return 1;
}
4.职工的信息卡内容包括:工号(字符串型)、姓名(字符串型)和出生时间(结构体型,包括年、月、日)三项
1)定义存储职工信息的单向链表的结点类型;
2)编写函数,由键盘依次输入职工的信息,按工号顺序创建一个用于管理职工信息的单向链表。直到输入的工号为“0000”为之。要求边录入边建立链表,不允许先建立链表后,再排序。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct date {
int y,m,d;
} date;
typedef struct teacher {
char id[10];
char name[10];
struct date birthdate;
struct teacher *next;
} teacher;
struct teacher *create() {
struct teacher *head=NULL,*p1,*p2;
char tempid[10];
scanf("%s",&tempid);
while(strcmp(tempid,"0000")!=0) {
p1=(struct teacher *)malloc(sizeof(struct teacher));
strcpy(tempid,p1->id);
scanf("%s%d%d%d",&p1->name,&p1->birthdate.y,&p1->birthdate.m,&p1->birthdate.d);
if(head==NULL) {
head=p1;
p1->next=NULL;
} else {
p2=head;
while(strcmp(p1->id,p2->next->id)>0)
p2=p2->next;
p1->next=p2->next;
p2->next=p1;
}
scanf("%s",&tempid);
}
return head;
}
5.编写函数,把上题创建的单向链表存储到文件名为output.dat的二进制文件中。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct date {
int y,m,d;
} date;
typedef struct teacher {
char id[10];
char name[10];
struct date birthdate;
struct teacher *next;
} teacher;
void save(struct teacher *head) {
FILE *file;
if((file=fopen("output.txt","wb"))==NULL) {
printf("open error");
exit(0);
}
while(head!=NULL) {
fprintf(file,"%10s\n",head->id);
fprintf(file,"%10s",head->name);
fprintf(file,"%5d",head->birthdate.y);
fprintf(file,"%5d",head->birthdate.m);
fprintf(file,"%5d",head->birthdate.d);
head=head->next;
}
fclose(file);
}