由用户输入一个正整数n,分析出该正整数的每一位,然后将各位数字从大到小重新排序后得到正整数m,输出m和n的平均值。

#include <stdio.h>
#include <stdlib.h>

/**
 * 选择排序法
 * @param a     排序数组
 * @param len   元素个数
 */
void selction_sort(int a[], int len) {
    int i, j, t;
    for (i = 0; i < len - 1; i++) {
        for (j = i + 1; j < len; j++) {
            if (a[i] < a[j]) {
                t = a[i];
                a[i] = a[j];
                a[j] = t;
            }
        }
    }
}

void main() {
    int m, n, t, i, c, *p;
    /*输入数字n*/
    scanf("%d", &n);
    /*分析位数c*/
    t = n;
    c = 0;
    while (t > 0) {
        c++;
        t /= 10;
    }
    /*分解数字n*/
    t = n;
    i = 0;
    p = (int *) malloc(sizeof(int) * c);
    while (t > 0) {
        p[i++] = t % 10;
        t /= 10;
    }
    /*排序数组p*/
    selction_sort(p, c);
    /*数组还原m*/
    m = 0;
    i = 0;
    while (i < c) {
        m *= 10;
        m += p[i++];
    }
    /*输出结果*/
    printf("n = %d\n", n);
    printf("m = %d\n", m);
    printf("(m + n) / 2 = %lf", ((m + n) / 2.0));
}

猜你喜欢

转载自blog.csdn.net/qq_38490457/article/details/106016489
今日推荐