1.编写函数int find(char *s1,char *s2),统计字符串s2在s1中出现的次数。其中字符串以'\0'为结束符
#include <stdio.h>
int strcmp(char *s1,char *s2) {
int i=0;
while(s2[i]!='\0')
if(s1[i]!=s2[i])
return 0;
else
i++;
return 1;
}
int strlen(char *s) {
int i=0;
while(s[i]!='\0')
i++;
return i;
}
int find(char *s1,char *s2) {
int times=0;
for(int i=0; i<(strlen(s1)-strlen(s2)+1); i++)
if(strcmp(s1+i,s2))
times++;
return times;
}
int main() {
char s1[]="abb3abb2abbabbabbbbbbb";
char s2[]="abb";
printf("time = %d",find(s1,s2));
}
2.编写递归函数,计算一个非负整数的所有组成数字的和。
#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));
}
3.每条购物记录包含产品名称,单价,数量,花费总额等信息,编写函数create,实现从文件中读入所有购物记录,构建一个单链表,假定文件中存储信息与结构体信息格式对应,要求文件名有函数的形式参量传入
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
char name[20];
int price;
int count;
int sum;
struct node *next;
} node;
struct node *create(char *filename) {
FILE *file;
if((file=fopen(filename,"r"))==NULL) {
printf("open error");
exit(0);
}
struct node *head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
struct node *rear=head;
while(!feof(file)) {
struct node *p=(struct node *)malloc(sizeof(struct node));
fscanf(file,"%s %lf,%d %lf",&p->name,&p->price,&p->count,&p->sum);
rear->next=p;
rear=p;
}
rear->next=NULL;
fclose(file);
return head->next;
}
4.假设input1.txt和input2.txt中分别存放了两个人的所有购物记录,编写函数,完成如下工作
利用上题的create函数分别构建单链表
计算每个人的购物总开销
返回两个人购物总开销的差值
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
char name[20];
int price;
int count;
int sum;
struct node *next;
} node;
struct node *create(char *filename) {
FILE *file;
if((file=fopen(filename,"r"))==NULL) {
printf("open error");
exit(0);
}
struct node *head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
struct node *rear=head;
while(!feof(file)) {
struct node *p=(struct node *)malloc(sizeof(struct node));
fscanf(file,"%s %lf,%d %lf",&p->name,&p->price,&p->count,&p->sum);
rear->next=p;
rear=p;
}
rear->next=NULL;
fclose(file);
return head->next;
}
int getcount(struct node *head) {
int sum=0;
struct node *p=head;
while(p!=NULL) {
sum+=p->sum;
p=p->next;
}
return sum;
}
int getdif() {
struct node *head1=create("input1.txt");
struct node *head2=create("input2.txt");
int sum1=getcount(head1);
int sum2=getcount(head2);
return sum1-sum2;
}