C语言——指针(1.6指针的实际应用[结合数组的排序问题])

练习:

例题1.6利用数组,指针,函数等解决实际问题中成绩的排序问题

#include <stdio.h>
#define N 40
int main()
{
    int n,i,order;
    int score[N];
    printf("Total students are:\n");
    scanf("%d",&n);//输入学生成绩个数
    printf("Input students 's score:\n");
    for(i=0;i<n;i++)
    {
        scanf("%4d",&score[i]);//
    }
    printf("Input your order:1 or 2:\n");//输入要选择的指令
    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("\n");
}

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

感兴趣的小伙伴可以自己敲一敲代码运行试试!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值