• C和指针 第十三章 习题


    1,1标准输入读入字符,统计各类字符所占百分比

    #include <stdio.h>
    #include <ctype.h>
    
    //不可打印字符
    int isunprint(int ch){
        return !isprint(ch);
    }
    
    //转换表,储存各个判断函数指针
    int (*tables[])(int) = {iscntrl, isspace, isdigit, islower, isupper, ispunct, isunprint};
    
    int main()
    {
        int count[7] = {0};
        int ch;
        int idx;
    
        while((ch = getchar()) != EOF){
            //转换表中的函数进行测试,如果符合对应的数组项+1
            for(idx = 0; idx < 7; idx++){
                if(tables[idx](ch)){
                    count[idx]++;
                }
            }
        }
    
        for(idx = 0; idx < 7; idx++){
            printf("%d
    ", count[idx]);
        }
    
        return 0;
    }
    

    运行结果:

    1.4 编写sort函数,对任何类型数组进行排序

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    void sort(void *array, unsigned length, unsigned int size, int(*compare)(void const *value1, void const *value2))
    {
        //循环变量
        int idx, idy;
        void *temp = malloc(size);
    
        for (idx = 0; idx < length - 1; idx++) {
            for (idy = idx + 1; idy < length; idy++) {
                //通过字节复制,交换位置,由于array是void类型的,所以需要根据size来进行偏移,找到对应的元素地址
                if (compare(array + (idx * size), array + idy * size) == 1) {
                    //array是指向数组的指针,根据元素大小,得到元素地址
                    memcpy(temp, array + idx * size, size);
                    memcpy(array + idx * size, array + idy * size, size);
                    memcpy(array + idy * size, temp, size);
                }
            }
        }
    }
    
    int int_compare(void const *value1, void const *value2)
    {
        if (*(int *)value1 == *(int *)value2) {
            return 0;
        }
        else if (*(int *)value1 <= *(int *)value2) {
            return -1;
        }
        else {
            return 1;
        }
    }
    
    int main()
    {
        int array[] = { 1, 4, 5, 2, 3, 8, 6, -10};
        for (int idx = 0; idx < 8; idx++) {
            printf("%d	", array[idx]);
        }
        printf("
    ");
        sort(array, 8, 4, int_compare);
    
        for (int idx = 0; idx < 8; idx++) {
            printf("%d	", array[idx]);
        }
    
        return 0;
    }
    

    运行:

  • 相关阅读:
    ccache——/root/.ccache
    Ionic 2 | Tutorial | Let’s Create Our First Application
    Ionic 2 Tutorial
    搭建移动端框架Ionic+Genymotion开发环境
    【2020】输出矩阵
    【2015】给一个不多于三位的正整数,求出它是几位数,并分别打印出各位上的数字。
    【2021】小球走过的路程
    【2022】余料最少
    【2023】将十进制数转化为二进制数
    【2024】求X到Y之间的整数和
  • 原文地址:https://www.cnblogs.com/yangxunwu1992/p/5854519.html
Copyright © 2020-2023  润新知