K&R的名著:<C程序设计语言>小程序总结3

来源:互联网 发布:医院数据集成平台架构 编辑:程序博客网 时间:2024/05/16 09:05

1、printd函数:打印十进制数n

/*用于解决低位先于高位生成,但是必须与此向反的秩序打印*/

void printd(int n)
{
    if (n < 0)
       putchar('-');
       n = - n;
    if (n / 10)
        printd(n / 10);
    putchar(n%10 + '0');
}
2、快速排序qsort函数:以递增顺序对v[left] ...v[right]进行排序

 

void qsort(int v[], int left, int right)

{

    int i, last;

    void swap(int v[], int left ,int right);

     if (left >= right)

        return;

    swap(v, left,((left +right) / 2));

    last = left;

    for (i = left + 1; i <= right; i++)

       if (v[i] < v[left])

          swap(v,++last, i);

    swap(v, left, right);

    qsort(v, left, last-1);

    qsort(v, last+1,right);

}
void swap(int v[], int i, int j)
{
   int temp;

   temp = v[i];
   v[i] = v[j];
   v[j] = temp;
}

 

#include <stdio.h>#include <string.h>void qsort(char*v[], int left, int right){int i, last;void swap(char*v[], int i, int j);if (left >= right)return;swap(v, left, (left + right) / 2);last = left;for (i = left + 1; i <= right; ++i)    if (strcmp(v[i],v[left]) < 0)swap(v, ++last, i);swap(v, left, last);qsort(v, left, last-1);qsort(v,last+1,right);}void swap(char*v[], int i, int j){char *temp;temp = v[i];v[i] = v[j];v[j] = temp;}void main(void){int i;char *lineptr[3]={"hello","hill","new"};qsort(lineptr,0,2);for(i =0;i <3; i++)//while(*p != '\0')printf("the sorted v[%d] is %s\n",i,lineptr[i]);}


 


3、宏替换a、带参数的宏替换                b、形参不能用带引号的字符串替换  c、宏扩展##连接实参方法   #define max(A, B) ((A) > (B) ? (A) : (B))
#define dprint(expr) printf(#expr " = %g\n",expr)
#define paste(front, back) front##back   paste(name,1)  -> name1#define swap(t,x,y) { t _z;\
                      _z = y;
                      y = x;
                      x = _z;                     
                    }4、条件包含为保证hdr.h文件的内容只被包含一次,可以用如下方式处理:#if !defined(HDR)   //#ifndef HDR#define HDR         //define HDR...#endif

 

 

原创粉丝点击