C语言——指针(1.6指针的实际应用[结合数组的排序问题])
练习:
例题1.6利用数组,指针,函数等解决实际问题中成绩的排序问题
#include <stdio.h>
#define N 40
int main()
{
int n,i,order;
int score[N];
printf("Total students are:
");
scanf("%%d",&n);//输入学生成绩个数
printf("Input students 's score:
");
for(i=0;i<n;i++)
{
scanf("%%4d",&score[i]);//
}
printf("Input your order:1 or 2:
");//输入要选择的指令
scanf("%%d",&order);
if(order==1)
{
printf_orig(score,n);//输出原始成绩
printf_max_sorted(score,n);//输出按升序排列的成绩
}
else if(order==2)
{
printf_orig(score,n);//输出原始成绩
printf_min_sorted(score,n);//输出按降序排列的成绩
}
return 0;
}
void printf_orig(int score[],int n)//函数功能:输出原始成绩
{
int i;
printf("Original scores are:");
for(i=0;i<n;i++)
{
printf("%%d ",score[i]);
}
printf("
");
}
void printf_max_sorted(int score[],int n)//函数功能:输出升序成绩
{
int i,j;
printf("max_sorted:");
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(score[j]<score[i])
swap_score(&score[i],&score[j]);
}
}
for(i=0;i<n;i++)
printf("%%4d",score[i]);
}
void printf_min_sorted(int score[],int n)//函数功能:输出降序成绩
{
int i,j;
printf("min_sorted:");
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(score[j]>score[i])
swap_score(&score[i],&score[j]);
}
}
for(i=0;i<n;i++)
printf("%%4d",score[i]);
}
void swap_score(int *x,int *y)//函数功能:利用指针间接寻址,交换两个成绩
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
其结果运行如下
升序排列:
Total students are:
10
Input students 's score:
85 84 96 100 25 62 33 65 55 55
Input your order:1 or 2:
1
Original scores are:85 84 96 100 25 62 33 65 55 55
max_sorted: 25 33 55 55 62 65 84 85 96 100
降序排列:
Total students are:
10
Input students 's score:
85 85 96 45 60 56 75 85 95 39
Input your order:1 or 2:
2
Original scores are:85 85 96 45 60 56 75 85 95 39
min_sorted: 96 95 85 85 85 75 60 56 45 39
感兴趣的小伙伴可以自己敲一敲代码运行试试!