C语言练习5

典型程序

输入行排序

   1    #include <stdio.h>
   2    #include <string.h>
   3 
   4    #define MAXLINES 5000     /* max #lines to be sorted */
   5 
   6    char *lineptr[MAXLINES];  /* pointers to text lines */
   7 
   8    int readlines(char *lineptr[], int nlines);
   9    void writelines(char *lineptr[], int nlines);
  10 
  11    void qsort(char *lineptr[], int left, int right);
  12 
  13    /* sort input lines */
  14    main()
  15    {
  16        int nlines;     /* number of input lines read */
  17 
  18        if ((nlines = readlines(lineptr, MAXLINES)) >= 0) {
  19            qsort(lineptr, 0, nlines-1);
  20            writelines(lineptr, nlines);
  21            return 0;
  22        } else {
  23            printf("error: input too big to sort\n");
  24            return 1;
  25        }
  26    }
  27 
  28    #define MAXLEN 1000  /* max length of any input line */
  29    int getline(char *, int);
  30    char *alloc(int);
  31 
  32    /* readlines:  read input lines */
  33    int readlines(char *lineptr[], int maxlines)
  34    {
  35        int len, nlines;
  36        char *p, line[MAXLEN];
  37 
  38        nlines = 0;
  39        while ((len = getline(line, MAXLEN)) > 0)
  40            if (nlines >= maxlines || p = alloc(len) == NULL)
  41                return -1;
  42            else {
  43                line[len-1] = '\0';  /* delete newline */
  44                strcpy(p, line);
  45                lineptr[nlines++] = p;
  46            }
  47        return nlines;
  48    }
  49 
  50    /* writelines:  write output lines */
  51    void writelines(char *lineptr[], int nlines)
  52    {
  53        int i;
  54 
  55        for (i = 0; i < nlines; i++)
  56            printf("%s\n", lineptr[i]);
  57    }
  58    /* qsort:  sort v[left]...v[right] into increasing order */
  59    void qsort(char *v[], int left, int right)
  60    {
  61        int i, last;
  62        void swap(char *v[], int i, int j);
  63 
  64        if (left >= right)  /* do nothing if array contains */
  65            return;         /* fewer than two elements */
  66        swap(v, left, (left + right)/2);
  67        last = left;
  68        for (i = left+1; i <= right; i++)
  69            if (strcmp(v[i], v[left]) < 0)
  70                swap(v, ++last, i);
  71        swap(v, left, last);
  72        qsort(v, left, last-1);
  73        qsort(v, last+1, right);
  74    }
  75    /* swap:  interchange v[i] and v[j] */
  76    void swap(char *v[], int i, int j)
  77    {
  78        char *temp;
  79 
  80        temp = v[i];
  81        v[i] = v[j];
  82        v[j] = temp;
  83    }

命令行参数指定查找字符串

   1    #include <stdio.h>
   2    #include <string.h>
   3    #define MAXLINE 1000
   4 
   5    int getline(char *line, int max);
   6 
   7    /* find:  print lines that match pattern from 1st arg */
   8    main(int argc, char *argv[])
   9    {
  10        char line[MAXLINE];
  11        int found = 0;
  12 
  13        if (argc != 2)
  14            printf("Usage: find pattern\n");
  15        else
  16            while (getline(line, MAXLINE) > 0)
  17                if (strstr(line, argv[1]) != NULL) {
  18                    printf("%s", line);
  19                    found++;
  20                }
  21        return found;
  22    }

函数指针

   1    #include <stdio.h>
   2    #include <string.h>
   3 
   4    #define MAXLINES 5000     /* max #lines to be sorted */
   5    char *lineptr[MAXLINES];  /* pointers to text lines */
   6 
   7    int readlines(char *lineptr[], int nlines);
   8    void writelines(char *lineptr[], int nlines);
   9 
  10    void qsort(void *lineptr[], int left, int right,
  11               int (*comp)(void *, void *));
  12    int numcmp(char *, char *);
  13 
  14    /* sort input lines */
  15    main(int argc, char *argv[])
  16    {
  17        int nlines;        /* number of input lines read */
  18        int numeric = 0;   /* 1 if numeric sort */
  19 
  20        if (argc > 1 && strcmp(argv[1], "-n") == 0)
  21            numeric = 1;
  22        if ((nlines = readlines(lineptr, MAXLINES)) >= 0) {
  23            qsort((void**) lineptr, 0, nlines-1,
  24              (int (*)(void*,void*))(numeric ? numcmp : strcmp));
  25            writelines(lineptr, nlines);
  26            return 0;
  27        } else {
  28            printf("input too big to sort\n");
  29            return 1;
  30        }
  31    }
  32 
  33    /* qsort:  sort v[left]...v[right] into increasing order */
  34    void qsort(void *v[], int left, int right,
  35               int (*comp)(void *, void *))
  36    {
  37        int i, last;
  38 
  39        void swap(void *v[], int, int);
  40 
  41        if (left >= right)    /* do  nothing if array contains */
  42            return;           /* fewer than two elements */
  43        swap(v, left, (left + right)/2);
  44        last = left;
  45        for (i = left+1; i <= right;  i++)
  46            if ((*comp)(v[i], v[left]) < 0)
  47                swap(v, ++last, i);
  48        swap(v, left, last);
  49        qsort(v, left, last-1, comp);
  50        qsort(v, last+1, right, comp);
  51    }
  52 
  53    #include <stdlib.h>
  54 
  55    /* numcmp:  compare s1 and s2 numerically */
  56    int numcmp(char *s1, char *s2)
  57    {
  58        double v1, v2;
  59 
  60        v1 = atof(s1);
  61        v2 = atof(s2);
  62        if (v1 < v2)
  63            return -1;
  64        else if (v1 > v2)
  65            return 1;
  66        else
  67            return 0;
  68 

关键字统计

   1    #include <stdio.h>
   2    #include <ctype.h>
   3    #include <string.h>
   4 
   5    #define MAXWORD 100
   6 
   7    struct key {
   8        char *word;
   9        int count;
  10    } keytab[] = {
  11        "auto", 0,
  12        "break", 0,
  13        "case", 0,
  14        "char", 0,
  15        "const", 0,
  16        "continue", 0,
  17        "default", 0,
  18        /* ... */
  19        "unsigned", 0,
  20        "void", 0,
  21        "volatile", 0,
  22        "while", 0
  23    };
  24 
  25 
  26    int getword(char *, int);
  27    int binsearch(char *, struct key *, int);
  28 
  29    /* count C keywords */
  30    main()
  31    {
  32        int n;
  33        char word[MAXWORD];
  34 
  35        while (getword(word, MAXWORD) != EOF)
  36            if (isalpha(word[0]))
  37                if ((n = binsearch(word, keytab, NKEYS)) >= 0)
  38                    keytab[n].count++;
  39        for (n = 0; n < NKEYS; n++)
  40            if (keytab[n].count > 0)
  41                printf("%4d %s\n",
  42                    keytab[n].count, keytab[n].word);
  43        return 0;
  44    }
  45 
  46    /* binsearch:  find word in tab[0]...tab[n-1] */
  47    int binsearch(char *word, struct key tab[], int n)
  48    {
  49        int cond;
  50        int low, high, mid;
  51 
  52        low = 0;
  53        high = n - 1;
  54        while (low <= high) {
  55            mid = (low+high) / 2;
  56            if ((cond = strcmp(word, tab[mid].word)) < 0)
  57                high = mid - 1;
  58            else if (cond > 0)
  59                low = mid + 1;
  60            else
  61                return mid;
  62        }
  63        return -1;
  64    }
  65    /* getword:  get next word or character from input */
  66    int getword(char *word, int lim)
  67    {
  68        int c, getch(void);
  69        void ungetch(int);
  70        char *w = word;
  71 
  72        while (isspace(c = getch()))
  73            ;
  74        if (c != EOF)
  75            *w++ = c;
  76        if (!isalpha(c)) {
  77            *w = '\0';
  78            return c;
  79        }
  80        for ( ; --lim > 0; w++)
  81            if (!isalnum(*w = getch())) {
  82                ungetch(*w);
  83                break;
  84            }
  85        *w = '\0';
  86        return word[0];
  87    }

关键字统计指针版

   1    #include <stdio.h>
   2    #include <ctype.h>
   3    #include <string.h>
   4    #define MAXWORD 100
   5 
   6    int getword(char *, int);
   7    struct key *binsearch(char *, struct key *, int);
   8 
   9    /* count C keywords; pointer version */
  10    main()
  11    {
  12        char word[MAXWORD];
  13        struct key *p;
  14 
  15        while (getword(word, MAXWORD) != EOF)
  16            if (isalpha(word[0]))
  17                if ((p=binsearch(word, keytab, NKEYS)) != NULL)
  18                    p->count++;
  19        for (p = keytab; p < keytab + NKEYS; p++)
  20            if (p->count > 0)
  21                printf("%4d %s\n", p->count, p->word);
  22        return 0;
  23    }
  24 
  25    /* binsearch: find word in tab[0]...tab[n-1] */
  26    struct key *binsearch(char *word, struck key *tab, int n)
  27    {
  28        int cond;
  29        struct key *low = &tab[0];
  30        struct key *high = &tab[n];
  31        struct key *mid;
  32 
  33        while (low < high) {
  34            mid = low + (high-low) / 2;
  35            if ((cond = strcmp(word, mid->word)) < 0)
  36                high = mid;
  37            else if (cond > 0)
  38                low = mid + 1;
  39            else
  40                return mid;
  41        }
  42        return NULL;
  43    }

单链表自引用结构体

   1 #include <stdio.h>
   2 #include <stdlib.h>
   3 #include <string.h>
   4 
   5 #define MAXWORD 1000
   6 struct node {
   7     char *word;
   8     int count;
   9     struct node *next;
  10 };
  11 
  12 struct node*addlist(struct node *head, char *w);
  13 char *strdup(char *s);
  14 void listprint(struct node *p);
  15 
  16 main() {
  17     struct node *head = NULL;
  18     char word[MAXWORD];
  19     while(getword(word, MAXWORD)!=EOF)
  20         if(isalpha(word[0]))
  21             head = addlist(head, word);
  22     listprint(head);
  23     system("pause");
  24 }
  25 
  26 void listprint(struct node *p) {
  27     while(p!=NULL) {
  28         printf("%4d %s\n", p->count, p->word);
  29         p = p->next;
  30     }
  31 }
  32 
  33 struct node*addlist(struct node *head, char *w){
  34     int cond;
  35     struct node *p = head, *pre = NULL;
  36     while(p!=NULL) {
  37         cond=strcmp(w,p->word);
  38         if(cond == 0) {
  39             p->count ++;
  40             return head;
  41         } else if(cond > 0) {
  42             pre = p; p = p->next;
  43         } else
  44             break;
  45     }
  46     p =(struct node*)malloc(sizeof(struct node));
  47     p->word = strdup(w);
  48     p->count = 1;
  49     if(pre == NULL) {
  50         p->next = NULL;
  51         head = p;   
  52     } else {
  53         p->next = pre->next;
  54         pre->next = p;
  55     }
  56     return head;
  57 }
  58 
  59 char *strdup(char *s) {
  60     char *p = (char *)malloc(strlen(s)+1);
  61     strcpy(p, s);
  62     return p;
  63 }
  64 
  65 
  66 #define BUFSIZE 100
  67 char buf[BUFSIZE]; /* buffer for ungetch */ 
  68 int bufp = 0; /* next free position in buf */
  69 int getch(void) /* get a (possibly pushed-back) character */ 
  70 {
  71     return (bufp > 0) ? buf[--bufp] : getchar(); 
  72 }
  73 
  74 void ungetch(int c) /* push character back on input */ {
  75     if (bufp >= BUFSIZE)
  76         printf("ungetch: too many characters\n"); 
  77     else
  78         buf[bufp++] = c; 
  79 }
  80 
  81 int getword(char *word, int lim)
  82 {
  83     int c;
  84     char *w = word;
  85 
  86     while (isspace(c = getch()))
  87         ;
  88     if (c != EOF)
  89         *w++ = c;
  90     if (!isalpha(c)) {
  91         *w = '\0';
  92         return c;
  93     }
  94     for ( ; --lim > 0; w++)
  95         if (!isalnum(*w = getch())) {
  96             ungetch(*w);
  97             break;
  98         }
  99     *w = '\0';
 100     return word[0];
 101 }

变长参数列表

   1    #include <stdarg.h>
   2 
   3    /* minprintf: minimal printf with variable argument list */
   4    void minprintf(char *fmt, ...)
   5    {
   6        va_list ap; /* points to each unnamed arg in turn */
   7        char *p, *sval;
   8        int ival;
   9        double dval;
  10 
  11        va_start(ap, fmt); /* make ap point to 1st unnamed arg */
  12        for (p = fmt; *p; p++) {
  13            if (*p != '%') {
  14                putchar(*p);
  15                continue;
  16            }
  17            switch (*++p) {
  18            case 'd':
  19                ival = va_arg(ap, int);
  20                printf("%d", ival);
  21                break;
  22            case 'f':
  23                dval = va_arg(ap, double);
  24                printf("%f", dval);
  25                break;
  26            case 's':
  27                for (sval = va_arg(ap, char *); *sval; sval++)
  28                    putchar(*sval);
  29                break;
  30            default:
  31                putchar(*p);
  32                break;
  33            }
  34        }
  35        va_end(ap); /* clean up when done */
  36    }

文件访问

   1    #include <stdio.h>
   2 
   3    /* cat:  concatenate files, version 1 */
   4    main(int argc, char *argv[])
   5    {
   6        FILE *fp;
   7        void filecopy(FILE *, FILE *)
   8 
   9        if (argc == 1) /* no args; copy standard input */
  10            filecopy(stdin, stdout);
  11        else
  12           while(--argc > 0)
  13               if ((fp = fopen(*++argv, "r")) == NULL) {
  14                   printf("cat: can't open %s\n, *argv);
  15                   return 1;
  16               } else {
  17                  filecopy(fp, stdout);
  18                  fclose(fp);
  19               }
  20           return 0;
  21    }
  22 
  23     /* filecopy:  copy file ifp to file ofp */
  24     void filecopy(FILE *ifp, FILE *ofp)
  25     {
  26         int c;
  27 
  28         while ((c = getc(ifp)) != EOF)
  29             putc(c, ofp);
  30     }

选择题

下列程序执行后的输出结果是 A 6 B 7 C 8 D 9

   1 void func(int *a,int b[]) {
   2     b[0]=*a+6; 
   3 }
   4 main() { 
   5     int a,b[5];
   6     a=0;
   7     b[0]=3;
   8     func(&a,b);  
   9     printf("%d\n,b[0]);
  10 }

下列程序的输出结果是 A 4 B 6 C 8 D 10

   1 int b=2;
   2 int func(int *a) { 
   3     b += *a; 
   4     return b;
   5 }
   6 main() { 
   7     int a=2, res=2;
   8     res += func(&a);
   9     printf("%d\n",res);
  10 }

下列程序的输出结果是 A 5 B 6 C 7 D 8

   1 struct abc { 
   2     int a, b, c; 
   3 };
   4 main() { 
   5     struct abc  s[2]={{1,2,3},{4,5,6}}; 
   6     int t;
   7     t=s[0],a+s[1],b;
   8     printf("%d\n",t);
   9 }

语句printf("a\bre\'hi\'y\\\bou\n");的输出结果是   A a\bre\'hi\'y\\\bou            B a\bre\'hi\'y\bou     C re'hi'you                     D abre'hi'y\bou

设已有定义: char *st="how are you"; 下列程序段中正确的是

     A) char  a[11], *p;  strcpy(p=a+1,&st[4]);
     B) char  a[11];      strcpy(++a, st);
     C) char  a[11];      strcpy(a, st);
     D) char  a[], *p;    strcpy(p=&a[1],st+2);

下列程序执行后的输出结果是 A you&me B you C me D err

   1 main() { 
   2     char  arr[2][4];
   3     strcpy(arr[0],"you");  
   4     strcpy(arr[1],"me");
   5     arr[0][3]='&';
   6     printf("%s\n",arr[0]);
   7 }

假定下列程序的可执行文件名为prg.exe,则在该程序所在的子目录下输入命令行: prg hello good<回车>后,程序的输出结果是  A) hello good   B) hg             C) hel           D) hellogood

   1 main()(int argc, char *argv[]) {
   2     int  i;
   3     if(argc<1)
   4         return;
   5     for(i=1;i<argc;i++) 
   6         printf("%c", *argv[i]);
   7 }

以下函数返回a所指数组中最小的值所在的下标值

   1 fun(int   *a,  int  n){   
   2     int   i,j=0,p;
   3     p=j;
   4     for(i=j;i<n;i++)
   5         if(a[i]<a[p])
   6             __________;
   7     return p;
   8 }

在下划线处应填入的是A) i=p             B) a[p]=a[i]       C) p=j            D) p=i

若有以下的定义:int t[3][2];能正确表示t数组元素地址的表达式是 A) &t[3][2]        B) t[3]            C) t[1]           D) t[2]

有如下定义

struct person{ 
    char  name[9]; 
    int age;
};
struct person   p[10]={
 "Johu",  17,
 "Paul",  19,
 "Mary",  18,
 "Adam",  16
};

根据上述定义,能输出字母M的语句是

A) printf("%c\n",p[3].name);
B) pfintf("%c\n",p[3].name[1]);
C) prinft("%c\n",p[2].name[1]);
D) printf("%c\n",p[2].name[0]);

以下对结构体类型变量的定义中,不正确的是

A) typedef struct aa                    
{
   int   n;                         
   float m;                             
}AA;                                 
AA td1; 

B) #define AA    struct aa
AA {
   int n;
   float m;
}td1;

C) struct                                  
{   
   int n;                                 
   float m;                                    
}aa;                                       
stuct aa td1;

D) struct
{    
   int n;
   float m;
}td1;

有如下程序

   1 main()
   2 {    
   3     char s[]="ABCD", *P;
   4     for(p=s+l; p<s+4; p++)   
   5         printf ("%s\n", p);
   6 }

该程序的输出结果是

A) ABCD            B) A               C) B              D) BCD
   BCD                B                  C                 CD
   CD                 C                  D                 D
   D                  D

有如下程序

   1 main()
   2 {    
   3    char ch[2][5]={"6937","8254"},*p[2];
   4    int i,j,s=0;
   5    for(i=0;i<2;i++)     
   6       p[i]=ch[i];
   7    for(i=0;i<2;i++)
   8       for(j=0;p[i][j]>'\0';j+=2)
   9          s=10*s+p[i][j]- '0';
  10    printf('%d\n',s);
  11 }

该程序的输出结果是 A) 69825           B) 63825           C) 6385           D) 693825

函数pi的功能是根据以下近似公式求π值:(π*π)/6=1+1/(2*2)+1/(3*3)+..+1/(n*n)。现在请你在下面的函数中填空,完成求π的功能

   1 #include <math.h>
   2 double pi(long n) {
   3    double s=0.0;    
   4    long i;
   5    for(i=1;i<=n;i++)
   6       s=s+_____________ ;
   7    return sqrt(6*s);
   8 }

下列程序段的输出结果是A) 2 1 4 3          B) 1 2 1 2          C) 1 2 3 4           D) 2 1 1 2

   1 void fun(int  *x, int  *y){
   2     printf("%d  %d", *x, *y);
   3     *x=3;
   4     *y=4;
   5 }
   6 main(){
   7    int  x=1,y=2;
   8    fun(&y,&x);
   9    printf("%d %d",x, y);
  10 }

下面程序把从终端读入的文本(用@作为文本结束标志)输出到一个名为bi.dat的新文件中。请填空。

   1 #include <stdio.h>
   2 main() {
   3    FILE  *fp;
   4    char  ch;
   5    if( (fp=fopen (_______________) ) == NULL)
   6       exit(0);
   7    while( (ch=getchar( )) !='@')
   8       putc (ch, fp);
   9    fclose(fp);
  10 }

以下各选项说明一种新的类型名,其中正确的是

A) typedef  v1  int;                    B) typedef  v2=int;
C) typedef  int  v3;            D) typedef  v4:  int;

以下程序的输出结果是

   1 main(){
   2    char  st[20]= "hello\0\t\\\";
   3    printf("%d%d\n",strlen(st),sizeof(st));
   4 }

A) 9 9                       B) 5 20                 C) 13 20        D) 20 20

以下选项中,不能正确赋值的是

A) char  s1[10]; s1="Ctest";
B) char  s2[]={'C', 't', 'e', 's', 't'};
C) char  s3[20]="Ctest";
D) char  *s4="Ctest";

若有定义:int aa[8];。则以下表达式中不能代表数组元aa[1]的地址的是 A) &aa[0]+1    B) &aa[1]       C) &aa[0]++   D) aa+1

以下程序的输出结果是

   1 union myun
   2 {   
   3    struct{   int  x, y, z; } u;
   4    int  k;
   5 } a;
   6 main(){
   7    a.u.x=4; a.u.y=5; a.u.z=6;
   8    a.k=0;
   9    printf(%d\n”,a.u.x);
  10 }

A) 4                 B) 5                    C) 6                    D) 0

下面的程序执行后,文件test中的内容是

   1 #include   <stdio.h>
   2 void fun(char   *fname.,char   *st) {
   3     FILE  *myf;
   4     int   i;
   5     myf = fopen(fname,"w");
   6     for(i=0; i<strlen(st); i++)
   7         putc(st[i], myf);
   8     fclose(myf);
   9 }
  10 main()
  11 {
  12    fun("test", "new world"); 
  13    fun("test","hello,");

A)hello,             B)new worldhello,       C)new world             D) hello, rld

C语言练习5 (2008-02-23 15:34:09由localhost编辑)