the c programing language chap5 : pointer and array

finally 课后题

有很多题目都是以前函数的指针处理,因为我是复习对这个概念理解的还不错,加上时间有限,并且网上也都有答案。继续下一章,
/*the c programing language chap5*/
#include "stdfs.h"
extern int getch();
extern void ungetch(int x);
/* 5-1 getint : get next integer from input into *pm */
int getint(int *pm)
{
    int cr;
    int sign;// sign the - or + 
    while (isspace(cr = getch()))/*skip white space */
        ;

    if (!isdigit(cr) && cr != '-' && cr != '+' && cr != EOF) {
       // ungetch(cr); //this statement will cause infiniti loop if not annotate it
        return 0;
    }

    sign = (cr == '-') ? (-1): 1;
    if (cr == '-' || cr == '+') {
        int pre = cr;
        if (!isdigit(cr = getch())) {
            if (cr != EOF)
                ungetch(cr);
            ungetch(pre);
            return 0;
        }
    }

   for (*pm = 0; isdigit(cr); cr = getch())
       *pm = 10 * (*pm) + (cr - '0');
   *pm = (*pm) * sign;   
   if (cr != EOF)
       ungetch(cr);
   return cr;    
}
void test_getint()
{
    int pm, result;

    while ((result = getint(&pm)) != EOF) 
        printf("getint = %d return result = %d \n", pm, result);
}
/*
   5-2
getint : get next float from input into *pm
 */
int getfloat(float *pm)
{
    int cr;
    int sign;// sign the - or + 
    float power;//record the length of  decimal  
    while (isspace(cr = getch()))/*skip white space */
        ;

    if (!isdigit(cr) && cr != '-' && cr != '+' && cr != '.' && cr != EOF) {
        // ungetch(cr); //this statement will cause infiniti loop if not annotate it
        return 0;
    }

    sign = (cr == '-') ? (-1): 1;
    if (cr == '-' || cr == '+') {
        int pre = cr;
        if (!isdigit(cr = getch())) {
            if (cr != EOF)
                ungetch(cr);
            ungetch(pre);
            return 0;
        }
    }

    for (*pm = 0.0; isdigit(cr); cr = getch())
        *pm = 10.0 * (*pm) + (cr - '0');

    if (cr == '.'){
        cr = getch();
        for (power = 1.0; isdigit(cr); cr = getch()) {
            *pm = 10.0 * (*pm) + (cr - '0');
            power *= 10.0;
        }    
    *pm = (*pm)/power;                   
    }    

    *pm = (*pm) * sign;   
    if (cr != EOF)
        ungetch(cr);
    return cr;    
}
void test_getfloat()
{
    int result;
    float pm;

    while ((result = getfloat(&pm)) != EOF) 
        printf("getfloat =%5.3f return result = %d \n", pm, result);
}

main() {

        printf("getfloat =%13.2f return result = %d \n", 12.3, 12);
   test_getfloat(); 

}

你可能感兴趣的:(array,C语言,pointer,arithmetic)