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)
运行结果