数组结构day1 4.17

day1作业:

在堆区申请5个连续的存储空间,实现车辆信息的输入(品牌,颜色,价格)

1>调用函数在堆区申请空间

2>调用函数实现输入

3>调用函数对价格排序

思路:和正常的冒泡是一样的

注意点:

1>if(条件) 条件是价格的比较 (p+j)->price (p+j+1)->price

2> 交换的是整个车的信息

例如: (p+j)表示整个车的地址

*(p+j)表示整个车的信息

交换的是*(p+j) 和*(p+j+1) 对应的整体信息

3> 注意中间变量t的类型,应该是结构体类型

4>调用函数输出

5>释放堆区空间

please input number->5 
please input name5
please input color5
please input price5
please input name4
please input color4
please input price4
please input name1
please input color1
please input price1
please input name2
please input color2
please input price2
please input name3
please input color3
please input price3
1	1	1.00
2	2	2.00
3	3	3.00
4	4	4.00
5	5	5.00
linux@linux:~/shuju/day1/test4$ cat main.c
#include "fun.h"

int main(int argc,char * argv[])
{
	int n;
	printf("please input number->");
	scanf("%d",&n);
	struct CAR *p = creat(n);
	Input(p,n);
	Bubble (p,n);
	Output(p,n);
	Free(p);

	return 0;

}
linux@linux:~/shuju/day1/test4$ cat fun.c
#include "fun.h"

struct CAR *creat(int n)
{
	struct CAR *p = (struct CAR *)malloc(sizeof(struct CAR)*n);
	if(p == NULL)
	{
		printf("error");
		return NULL;
	}

	return p;
}
void Input(struct CAR *p,int n)
{
	int i;
	for (i = 0;i<n;i++)
	{
		printf("please input name");
		scanf("%s",(p+i)->name);
		printf("please input color");
		scanf("%s",(p+i)->color);
		printf("please input price");
		scanf("%f",&(p+i)->price);
	}
}
void Output(struct CAR *p,int n)
{
	int i;
	for (i = 0;i<n;i++)
	{
		printf("%s\t%s\t%.2f\n",(p+i)->name,(p+i)->color,(p+i)->price);
	}
}
int *Free(struct CAR *p)
{
	if(p == NULL)
	{
		return NULL;
	}
	free(p);
	p == NULL;
}
void Bubble (struct CAR *p,int n)
{
	int i,j,count = 0;
	struct CAR temp;
	for (i = 1;i<n;i++)
	{
		for (j = 0;j<n-i;j++)
		{
			if((p+j)->price > (p+j+1)->price)
			{
				temp = *(p+j);
				*(p+j) = *(p+j+1);
				*(p+j+1) = temp;
				count++;
			}
		}
		if(count == 1)
			break;
	}
}
linux@linux:~/shuju/day1/test4$ cat fun.h
#ifndef __FUN_H_
#define __FUN_H_

#include <stdio.h>
#include <stdlib.h>
struct CAR
{
	char name[10];
	char color[10];
	float price;
};
struct CAR *creat(int n);
void Input(struct CAR *p,int n);
void Output(struct CAR *p,int n);
int *Free(struct CAR *p);
void Bubble (struct CAR *p,int n);
#endif

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值