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