思维导图:
1、使用多文件编译
定义商品信息:商品名称,商品单价,商品购买个数,商品描述,循环输入购买的商品,按单价排序,输出商品信息,计算最贵的商品以及一共花了多少钱?
在create函数,请实现在堆区申请内存5个连续的内存
在input函数,请实现循环输入购买的商品
在bubble函数,请实现按单价排序
在Max函数,计算最贵的商品名称
在Money函数,计算共花了多少钱
在output函数,请实现输出
在free_space函数,实现释放堆区内存
head1.h:
#ifndef __HEAD1_H__
#define __HEAD1_H__
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct Shoppings
{
char name[20];
int price;
int counts;
char describe[20];
};
struct Shoppings *create();
struct Shoppings *input(struct Shoppings *p);
struct Shoppings *bubble(struct Shoppings *p);
struct Shoppings *Max(struct Shoppings *p);
struct Shoppings *Money(struct Shoppings *p);
struct Shoppings *output(struct Shoppings *p);
struct Shoppings *free_space(struct Shoppings *p);
#endif
text1.c:
#include "head1.h"
struct Shoppings *create()
{
struct Shoppings *p=(struct Shoppings *)malloc(sizeof(struct Shoppings)*5);
if(NULL==p)
return NULL;
return p;
}
struct Shoppings *input(struct Shoppings *p)
{
for(int i=0;i<5;i++)
{
printf("输入第%d个商品:",i+1);
scanf("%s",(p+i)->name);
printf("输入第%d个商品的价格:",i+1);
scanf("%d",&(p+i)->price);
printf("输入第%d个商品的个数:",i+1);
scanf("%d",&(p+i)->counts);
printf("输入第%d个商品的描述:",i+1);
scanf("%s",(p+i)->describe);
}
}
struct Shoppings *bubble(struct Shoppings *p)
{
int t;
for(int i=1;i<5;i++)
{
for(int j=0;j<5-i;j++)
{
if((p+j)->price>(p+j+1)->price)
{
struct Shoppings t=*(p+j);
*(p+j)=*(p+j+1);
*(p+j+1)=t;
}
}
}
for(int i=0;i<5;i++)
{
printf("%d\t",(p+i)->price);
}
printf("\n");
return 0;
}
struct Shoppings *Max(struct Shoppings *p)
{
int max=p->price;
int maxi=0;
{
for(int i=0;i<5;i++)
{
if(max<(p+i)->price)
{
max=(p+i)->price;
maxi=i;
}
}
}
printf("最贵的商品名称为:%s,是%d元\n",(p+4)->name,(p+4)->price);
}
struct Shoppings *Money(struct Shoppings *p)
{
int sum=0;
for(int i=0;i<5;i++)
{
sum +=(p+i)->price*(p+i)->counts;
}
printf("总共花了%d元\n",sum);
}
struct Shoppings *output(struct Shoppings *p)
{
printf("商品名\t价格\t个数\t描述\n");
for(int i=0;i<5;i++)
{
printf("%s\t%d\t%d\t%s\n",(p+i)->name,(p+i)->price,(p+i)->counts,(p+i)->describe);
}
}
struct Shoppings *free_space(struct Shoppings *p)
{
if(NULL==p)
return NULL;
free(p);
p=NULL;
}
ms.c:
#include "head1.h"
int main(int argc, const char *argv[])
{
struct Shoppings *p=create();
input(p);
bubble(p);
Max(p);
Money(p);
output(p);
p=free_space(p);
return 0;
}
运行结果: