高级语言讲义2022软专(仅高级语言部分)

文章介绍了C语言中的函数实现,包括统计字符串出现次数、递归计算整数组成数字之和,以及从文件构建购物记录链表并计算总开销的差值。
摘要由CSDN通过智能技术生成

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;
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值