栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

练习:

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

#include
#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     {
        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     {
        printf("%d ",score[i]);
    }
    printf("n");
}

void printf_max_sorted(int score[],int n)//函数功能:输出升序成绩
{
    int i,j;
    printf("max_sorted:");
    for(i=0;i     {
        for(j=i+1;j         {
            if(score[j]                 swap_score(&score[i],&score[j]);
        }
    }
    for(i=0;i         printf("%4d",score[i]);
}

void printf_min_sorted(int score[],int n)//函数功能:输出降序成绩
{
    int i,j;
    printf("min_sorted:");
    for(i=0;i     {
        for(j=i+1;j         {
            if(score[j]>score[i])
                swap_score(&score[i],&score[j]);
        }
    }
    for(i=0;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

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/384331.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号