zoukankan      html  css  js  c++  java
  • 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;
    }
    

    运行:

  • 相关阅读:
    [AGC030F] Permutation and Minimum
    nginx
    Flex建立AS项目时,如何设定发布的舞台大小
    让Flex 支持VSS
    Flex编程实用技巧
    Flash/Flex学习笔记(57):实用技巧
    sql 2000 "无法执行查询,因为一些文件缺少或未注册"的解决办法
    Flash/Flex学习笔记(56):矩阵变换
    什么是反向代理,如何利用反向代理提高网站性能
    AS3及Flex的百条常用知识
  • 原文地址:https://www.cnblogs.com/yangxunwu1992/p/5854519.html
Copyright © 2011-2022 走看看