嵌入式学习-数据结构-Day1

Day1

思维导图

在这里插入图片描述

作业

使用多文件编辑,

定义商品信息:商品名称,商品单价,商品购买个数,商品描述,循环输入购买的商品,按单价排序,输出商品信息,计算最贵的商品以及一共花了多少钱?

在create函数,请实现在堆区申请内存5个连续的内存

在input函数,请实现循环输入购买的商品

在bubble函数,请实现按单价排序

在Max函数,计算最贵的商品名称

在Money函数,计算共花了多少钱

在output函数,请实现输出

在free_space函数。实现释放堆区内存

代码

head.h

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct Product 
{
	char name[20];
	int price;
	int quantity;
	char description[100];
};
struct Product *create();
void input(struct Product *p);
void bubble(struct Product *p);
void Max(struct Product *p);
int Money(struct Product *p);
void output(struct Product *p); 
struct Product *free_space(struct Product *p);

main.c

#include "head.h"
int main(int argc, const char *argv[])
{
	struct Product *p=create();
	input(p);
	bubble(p);
	int cost=Money(p);
	puts("the Product's message is:");
	output(p);
	Max(p);
	p=free_space(p);
	puts("the money spent is:");
	printf("%d\n",cost);
	return 0;
}

test.c

#include "head.h"
struct Product *create()
{
	struct Product *p=(struct Product *)malloc(sizeof(struct Product)*5);
	if(NULL==p)
		return NULL;
	return p;
}

void input(struct Product *p)
{
	for(int i=0;i<5;i++)
	{
		scanf("%s %d %d %s",(p+i)->name,&((p+i)->price),&((p+i)->quantity),(p+i)->description);
	}
}

void bubble(struct Product *p)
{
	for(int i=0;i<4;i++)
	{
		for(int j=0;j<4-i;j++)
		{
			if((p[j].price)<(p[j+1].price))
			{
				struct Product t=p[j];
				p[j]=p[j+1];
				p[j+1]=t;
			}
		}
	}
}

void Max(struct Product *p)
{
	int flag=0;
	int max=p[0].price;
	for(int i=0;i<5;i++)
	{
		if((p+i)->price>=max)
		{	
			max=(p+i)->price;
			flag=i;
		}
	}
	printf("the most expensive Product is:%s\n",p[flag].name);
}

int Money(struct Product *p)
{
	int sum=0;
	for(int i=0;i<5;i++)
	{
		sum+=(((p+i)->price)*((p+i)->quantity));
	}
	return sum;
}

void output(struct Product *p)
{
	for(int i=0;i<5;i++)
	{
		printf("name\t\tprice\t\tquantity\tdescription\n");
		printf("%-16s%-16d%-16d%-16s\n",(p+i)->name,(p+i)->price,(p+i)->quantity,(p+i)->description);
	}
}

struct Product *free_space(struct Product *p)
{
	if(NULL==p)
		return NULL;
	free(p);
	p=NULL;
	return p;
}

makefile

EXE=hello
OBJS=$(patsubst %.c,%.o,$(wildcard *.c))
CC=gcc
CFLAGS=-c -o

all:$(EXE)

$(EXE):$(OBJS)
	$(CC) $^ -o $@

%.o:%.c
	$(CC) $(CFLAGS) $@ $^
.PHONY:clean
clean:
	@rm $(OBJS) $(EXE)

运行结果
在这里插入图片描述

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值