The C programming language (second edition,KR) exercise(CHAPTER 4)

news2024/12/25 13:54:17

      E x c e r c i s e 4 − 1 Excercise\quad 4-1 Excercise41

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int strindex(char s[],char t[]);
int strrindex(char s[],char t[]);


int main(void) 
{
    char s[100]="qwoulddfsdfdsgdsgdsgdsouldasdasdasd";
    char t[100]="ould";	
    int l_index=strindex(s,t);
    int r_index=strrindex(s,t);	
	printf("l_index=%d\n",l_index);	
	printf("r_index=%d\n",r_index);		
    return 0;
}

int strindex(char s[],char t[])
{
    int i,j,k;
    for(i=0;s[i]!='\0' ;i++)
	{
		for(j=i,k=0;t[k]!='\0' && s[j]==t[k];j++,k++)
			;
		if((k>0)&&(t[k]=='\0'))
			return i;
		
	}		
	return -1;
}

int strrindex(char s[],char t[])
{
    int i,j,k;
	int t_len=strlen(t);
	int s_len=strlen(s);
	if(t_len>s_len)
	{
	    return -1;				
	}
	else
	{
        for(i=s_len-t_len;i>=0 ;i--)
	    {
	    	for(j=i,k=0;t[k]!='\0' && s[j]==t[k];j++,k++)
	    		;
	    	if((k>0)&&(t[k]=='\0'))
	    		return i;	    	
	    }		
	    return -1;
	}
}

      E x c e r c i s e 4 − 2 Excercise\quad 4-2 Excercise42:输出如图1所示。

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

double atof_myself(char s[]);


int main(void) 
{
    char s1[100]="123.789e1";
    char s2[100]="123456123456.789e-10";	
    char s3[100]="123.789";		
    double d1=atof_myself(s1);
    double d2=atof_myself(s2);
    double d3=atof_myself(s3);	
	printf("d1=%lf\n",d1);
	printf("d2=%lf\n",d2);	
	printf("d3=%lf\n",d3);		
    return 0;
}

double atof_myself(char s[])
{
	double val,power,power_more;
    int i,sign,sign_more,power_more_index;
    for(i=0;isspace(s[i]);i++);
	sign=(s[i]=='-')? -1:1;
	if((s[i]=='-')||(s[i]=='+'))
	{
		i++;
	}	
    for(val=0.0;isdigit(s[i]);i++)
	{
		val=10.0*val+(s[i]-'0');		
	}	
	if(s[i]=='.')
	{
		i++;
	}
    for(power=1.0;isdigit(s[i]);i++)
	{
		val=10.0*val+(s[i]-'0');
        power *=10.0;		
	}	
	if((s[i]=='e') ||(s[i]=='E'))
	{
		i++;
	    sign_more=(s[i]=='-')? -1:1;
	    if((s[i]=='-')||(s[i]=='+'))
	    {
	    	i++;
	    }	
        for(power_more_index=0;isdigit(s[i]);i++)
	    {
	    	power_more_index=10*power_more_index+(s[i]-'0');	
	    }
		power_more=1.0;
        for(i=0;i<power_more_index;i++)
		{
			power_more=power_more*10.0;			
		}	
	    if(sign_more==-1)
	    {
	        return ((sign * val/power)/power_more);    	    		    	
	    }
	    else
	    {
	        return ((sign * val/power)*power_more);  	
	    }		
	}
    else
    {
	    return (sign * val/power); 	   	
    }	
}
 
图1.

      E x c e r c i s e 4 − 3 Excercise\quad 4-3 Excercise43

#include <stdio.h>
#include <stdlib.h>   /* for atof() */
#include <math.h>     /* for fmod() */

#define MAXOP 100     /* max size of operand or operator */
#define NUMBER '0'    /* signal that a number was found */

int getop(char []);
void push(double);
double pop(void);


/* reverse Polish calculator */
int main()
{
    int type;
    double op2;
    char s[MAXOP];
    while ((type = getop(s)) != EOF) 
	{
        switch (type) 
		{
            case NUMBER:
                 push(atof(s));
                 break;
            case '+':
                 push(pop() + pop());
                 break;
            case '*':
                 push(pop() * pop());
                 break;
            case '-':
                 op2 = pop();
                 push(pop() - op2);
                 break;
            case '/':
                 op2 = pop();
                 if (op2 != 0.0)
                     push(pop() / op2);
                 else
                     printf("error: zero divisor\n");
                 break;
            case '%':
                 op2 = pop();
                 if (op2 != 0.0)
                     push(fmod(pop(),op2));
                 else
                     printf("error: zero divisor\n");
                 break;
            case '\n':
                 printf("\t%.8g\n", pop());
                 break;				 
            default:
                 printf("error: unknown command %s\n", s);
                 break;
        }
    }
    return 0;
}

#define MAXVAL 100   /* maximum depth of val stack */
int sp = 0;          /* next free stack position */
double val[MAXVAL];  /* value stack */

/* push: push f onto value stack */
void push(double f)
{
    if (sp < MAXVAL)
        val[sp++] = f;
    else
        printf("error: stack full, can't push %g\n", f);
}

/* pop: pop and return top value from stack */
double pop(void)
{
    if (sp > 0)
        return val[--sp];
    else 
	{
        printf("error: stack empty\n");
        return 0.0;
    }
}


#include <ctype.h>
int getch(void);
void ungetch(int);

/* getop: get next character or numeric operand */
int getop(char s[])
{
    int i, c;
    while ((s[0] = c = getch()) == ' ' || c == '\t');
    s[1] = '\0';
    if (!isdigit(c) && c != '.' && c != '-')
	{	
        return c; /* not a number */
	}

	if(c == '-')
	{
        i = 0;			
        c = getch();	
        s[++i] = c;			
	}
	else
	{
        i = 0;				
	}
	
    if (isdigit(c)) /* collect integer part */
        while (isdigit(s[++i] = c = getch()));
    if (c == '.') /* collect fraction part */
        while (isdigit(s[++i] = c = getch()));
    s[i] = '\0';
    if (c != EOF)
	{		
        ungetch(c);
	}
    if (i == 1 && s[0] == '-') // if s[0] == '-' && s[1] == '\0', return minus operator
        return '-';	
    return NUMBER;
}


#define BUFSIZE 100

char buf[BUFSIZE];   /* buffer for ungetch */
int bufp = 0;        /* next free position in buf */

int getch(void)      /* get a (possibly pushed-back) character */
{
    return (bufp > 0) ? buf[--bufp] : getchar();
}

void ungetch(int c) /* push character back on input */
{
    if (bufp >= BUFSIZE)
        printf("ungetch: too many characters\n");
    else
        buf[bufp++] = c;
}

      E x c e r c i s e 4 − 4 Excercise\quad 4-4 Excercise44

#include <stdio.h>
#include <stdlib.h>   /* for atof() */
#include <math.h>     /* for fmod() */

#define MAXOP 100     /* max size of operand or operator */
#define NUMBER '0'    /* signal that a number was found */

int getop(char []);
void push(double);
double pop(void);
void showTop(void);
void duplicate(void);
void swapItems(void);
void clearStack();

/* reverse Polish calculator */
int main()
{
    int type;
    double op2;
    char s[MAXOP];
    while ((type = getop(s)) != EOF) 
	{
        switch (type) 
		{
            case NUMBER:
                 push(atof(s));
                 break;
            case '+':
                 push(pop() + pop());
                 break;
            case '*':
                 push(pop() * pop());
                 break;
            case '-':
                 op2 = pop();
                 push(pop() - op2);
                 break;
            case '/':
                 op2 = pop();
                 if (op2 != 0.0)
                     push(pop() / op2);
                 else
                     printf("error: zero divisor\n");
                 break;
            case '%':
                 op2 = pop();
                 if (op2 != 0.0)
                     push(fmod(pop(),op2));
                 else
                     printf("error: zero divisor\n");
                 break;
/****************************************************/				 
            case '?':
                showTop();
                break;
            case '#':
                duplicate();
                break;
            case '~':
                swapItems();
                break;
            case '!':
                clearStack();	
                break;				
/****************************************************/				 
            case '\n':
                 printf("\t%.8g\n", pop());
                 break;				 
            default:
                 printf("error: unknown command %s\n", s);
                 break;
        }
    }
    return 0;
}

#define MAXVAL 100   /* maximum depth of val stack */
int sp = 0;          /* next free stack position */
double val[MAXVAL];  /* value stack */

/* push: push f onto value stack */
void push(double f)
{
    if (sp < MAXVAL)
        val[sp++] = f;
    else
        printf("error: stack full, can't push %g\n", f);
}

/* pop: pop and return top value from stack */
double pop(void)
{
    if (sp > 0)
        return val[--sp];
    else 
	{
        printf("error: stack empty\n");
        return 0.0;
    }
}

/**********************************************************/
void showTop(void)
{
    if(sp > 0)
        printf("Top of stack contains: %8g\n", val[sp-1]);
    else
        printf("The stack is empty!\n");
}


void duplicate(void)
{
    double temp = 0.0;	
    if(sp > 0)
    {
        temp = pop();
        push(temp);
        push(temp);				
	}
    else
        printf("The stack is empty!\n");	

}

void swapItems(void)
{
    double item1 = 0.0;
    double item2 = 0.0;	
    if(sp >= 2)
    {
        item1 = pop();
        item2 = pop();

        push(item1);
        push(item2);			
	}
    else
        printf("The stack is empty!\n");	
}

/* pop only returns a value if sp is greater than zero. So setting the
stack pointer to zero will cause pop to return its error */

void clearStack(void)
{
    sp = 0;
}

/**********************************************************/




#include <ctype.h>
int getch(void);
void ungetch(int);

/* getop: get next character or numeric operand */
int getop(char s[])
{
    int i, c;
    while ((s[0] = c = getch()) == ' ' || c == '\t');
    s[1] = '\0';
    if (!isdigit(c) && c != '.' && c != '-')
	{	
        return c; /* not a number */
	}

	if(c == '-')
	{
        i = 0;			
        c = getch();	
        s[++i] = c;			
	}
	else
	{
        i = 0;				
	}
	
    if (isdigit(c)) /* collect integer part */
        while (isdigit(s[++i] = c = getch()));
    if (c == '.') /* collect fraction part */
        while (isdigit(s[++i] = c = getch()));
    s[i] = '\0';
    // if (c != EOF)
	// {		
        // ungetch(c);
	// }
    if (i == 1 && s[0] == '-') // if s[0] == '-' && s[1] == '\0', return minus operator
        return '-';	
    return NUMBER;
}


#define BUFSIZE 100

char buf[BUFSIZE];   /* buffer for ungetch */
int bufp = 0;        /* next free position in buf */

int getch(void)      /* get a (possibly pushed-back) character */
{
    return (bufp > 0) ? buf[--bufp] : getchar();
}

void ungetch(int c) /* push character back on input */
{
    if (bufp >= BUFSIZE)
        printf("ungetch: too many characters\n");
    else
        buf[bufp++] = c;
}

      E x c e r c i s e 4 − 5 Excercise\quad 4-5 Excercise45

#include <stdio.h>
#include <stdlib.h>  
#include <math.h>   

#define MAXOP 100     /* max size of operand or operator */
#define NUMBER '0'    /* signal that a number was found */

int getop(char []);
void push(double);
double pop(void);
void showTop(void);
void duplicate(void);
void swapItems(void);
void clearStack();

/* reverse Polish calculator */
int main()
{
    int type;
    double op2;
    char s[MAXOP];
    while ((type = getop(s)) != EOF) 
	{
        switch (type) 
		{
            case NUMBER:
                 push(atof(s));
                 break;
            case '+':
                 push(pop() + pop());
                 break;
            case '*':
                 push(pop() * pop());
                 break;
            case '-':
                 op2 = pop();
                 push(pop() - op2);
                 break;
            case '/':
                 op2 = pop();
                 if (op2 != 0.0)
                     push(pop() / op2);
                 else
                     printf("error: zero divisor\n");
                 break;
            case '%':
                 op2 = pop();
                 if (op2 != 0.0)
                     push(fmod(pop(),op2));
                 else
                     printf("error: zero divisor\n");
                 break;
/****************************************************/				 
            case '?':
                showTop();
                break;
            case '#':
                duplicate();
                break;
            case '~':
                swapItems();
                break;
            case '!':
                clearStack();	
                break;				
/****************************************************/
/****************************************************/				 
            case '$':
                push(sin(pop()));
                break;
            case '@':
                push(exp(pop()));
                break;
            case '^':
                 op2 = pop();
                 push(pow(pop(),op2));
                break;				
/****************************************************/				 
            case '\n':
                 printf("\t%.8g\n", pop());
                 break;				 
            default:
                 printf("error: unknown command %s\n", s);
                 break;
        }
    }
    return 0;
}

#define MAXVAL 100   /* maximum depth of val stack */
int sp = 0;          /* next free stack position */
double val[MAXVAL];  /* value stack */

/* push: push f onto value stack */
void push(double f)
{
    if (sp < MAXVAL)
        val[sp++] = f;
    else
        printf("error: stack full, can't push %g\n", f);
}

/* pop: pop and return top value from stack */
double pop(void)
{
    if (sp > 0)
        return val[--sp];
    else 
	{
        printf("error: stack empty\n");
        return 0.0;
    }
}

/**********************************************************/
void showTop(void)
{
    if(sp > 0)
        printf("Top of stack contains: %8g\n", val[sp-1]);
    else
        printf("The stack is empty!\n");
}


void duplicate(void)
{
    double temp = 0.0;	
    if(sp > 0)
    {
        temp = pop();
        push(temp);
        push(temp);				
	}
    else
        printf("The stack is empty!\n");	

}

void swapItems(void)
{
    double item1 = 0.0;
    double item2 = 0.0;	
    if(sp >= 2)
    {
        item1 = pop();
        item2 = pop();

        push(item1);
        push(item2);			
	}
    else
        printf("The stack is empty!\n");	
}

/* pop only returns a value if sp is greater than zero. So setting the
stack pointer to zero will cause pop to return its error */

void clearStack(void)
{
    sp = 0;
}

/**********************************************************/




#include <ctype.h>
int getch(void);
void ungetch(int);

/* getop: get next character or numeric operand */
int getop(char s[])
{
    int i, c;
    while ((s[0] = c = getch()) == ' ' || c == '\t');
    s[1] = '\0';
    if (!isdigit(c) && c != '.' && c != '-')
	{	
        return c; /* not a number */
	}

	if(c == '-')
	{
        i = 0;			
        c = getch();	
        s[++i] = c;			
	}
	else
	{
        i = 0;				
	}
	
    if (isdigit(c)) /* collect integer part */
        while (isdigit(s[++i] = c = getch()));
    if (c == '.') /* collect fraction part */
        while (isdigit(s[++i] = c = getch()));
    s[i] = '\0';
    // if (c != EOF)
	// {		
        // ungetch(c);
	// }
    if (i == 1 && s[0] == '-') // if s[0] == '-' && s[1] == '\0', return minus operator
        return '-';	
    return NUMBER;
}


#define BUFSIZE 100

char buf[BUFSIZE];   /* buffer for ungetch */
int bufp = 0;        /* next free position in buf */

int getch(void)      /* get a (possibly pushed-back) character */
{
    return (bufp > 0) ? buf[--bufp] : getchar();
}

void ungetch(int c) /* push character back on input */
{
    if (bufp >= BUFSIZE)
        printf("ungetch: too many characters\n");
    else
        buf[bufp++] = c;
}

      E x c e r c i s e 4 − 6 Excercise\quad 4-6 Excercise46:其实这一题的意图似乎还是很模糊的,我这里的做法是提供26个变量(分别对应26个小写英文字母),然后再提供一个数组用来存储这26个变量的值。如果要对某个变量赋值可以类似 x = n n n . n n n x=nnn.nnn x=nnn.nnn来操作,其中 x x x表示26个小写英文字母中的任何一个, n n n . n n n nnn.nnn nnn.nnn表示即将赋值给变量的值,这个值可以为负数,负数的话在最前面需要加上 − - ,比如 − n n n . n n n -nnn.nnn nnn.nnn。某个变量在参与运算之前需要先进行赋值操作,否则可能拿到的是默认值 0.0 0.0 0.0,变量参加运算的一个例子为 a 8 + a8+ a8+实际是变量 a a a的值和8进行加法运算。这里还记录了最近赋值或参与运算的是那个变量,并且 _ \_ _符号对应的命令操作会将这个最近赋值或参与运算的变量以及对应的值打印出来。

#include <stdio.h>
#include <stdlib.h> 
#include <ctype.h>
#include <math.h>
#include <string.h> 

#define MAXOP     100     /* max size of operand or operator */
#define NUMBER    '0'     /* signal that a number was found */
#define SETVARIABLE 's'   /* signal that a variable is being assigned */
#define GETVARIABLE 'g'   /* signal that a variable is being retrieved */
#define NUMVARS 26        /* number of variables supported (a-z) */

enum boolean {FALSE, TRUE};


int getop(char []);
void push(double);
double pop(void);
void showTop(void);
void duplicate(void);
void swapItems(void);
void clearStack();
void view_stack();	


/* initially as space such that malformed use of '=' won't cause segfaults */
char last_recent = ' '; 
/* array to store the double values for variables. 
Supports variables a through z (lower case). Initial value is 0*/
double varVals[NUMVARS] = {0.0}; 

/* reverse Polish calculator */
int main()
{
    int type;
    double op2;
    char s[MAXOP];
    while ((type = getop(s)) != EOF) 
	{
        switch (type) 
		{
            case NUMBER:
                 push(atof(s));
                 break;
/****************************************************/				 
            case SETVARIABLE:
                 if (strlen(s) > 2 && s[1] == '=')
                 {
                     int v = s[0];           /* stores variable */
                     int i = 1;              /* start at 1 since while loop needed ++i for a few reasons */
                     while (s[++i] != '\0')  /* this removes the variable name= part of s e.g. if s == "a=123.45" after loop s == "123.45" */
                         s[i - 2] = s[i];    /* shifts chars two to the left by 2 */
                     s[i - 2] = '\0';        /* since '\0' isn't copied, terminate string manually */
                     varVals[v - 'a'] = atof(s); /* convert string to double and store it in array */
                 }
                 else
                     printf("error: set variable length too small or incorrectly formatted (%s)\n", s);
                 break;
            case GETVARIABLE:
                 push(varVals[s[0] - 'a']);  /* convert the variable name to stored value */
                 break;	
/****************************************************/				 
            case '+':
                 push(pop() + pop());
                 break;
            case '*':
                 push(pop() * pop());
                 break;
            case '-':
                 op2 = pop();
                 push(pop() - op2);
                 break;
            case '/':
                 op2 = pop();
                 if (op2 != 0.0)
                     push(pop() / op2);
                 else
                     printf("error: zero divisor\n");
                 break;
            case '%':
                 op2 = pop();
                 if (op2 != 0.0)
                     push(fmod(pop(),op2));
                 else
                     printf("error: zero divisor\n");
                 break;
/****************************************************/				 
            case '?':
                showTop();
                break;
            case '#':
                duplicate();
                break;
            case '~':
                swapItems();
                break;
            case '!':
                clearStack();	
                break;				
/****************************************************/
			 
            case '$':
                push(sin(pop()));
                break;
            case '@':
                push(exp(pop()));
                break;
            case '^':
                op2 = pop();
                push(pow(pop(),op2));
                break;									
            // case '\n':
                 // printf("\t%.8g\n", pop());
                 // break;
            case '\n':
                 view_stack();
                 break;	
            case '_':
                 printf("The last recently used variable is %c=%8g\n",last_recent, varVals[last_recent-'a']);
                 break;					 
            default:
                 printf("error: unknown command %s\n", s);
                 break;
        }
    }
    return 0;
}

#define MAXVAL 100   /* maximum depth of val stack */
int sp = 0;          /* next free stack position */
double val[MAXVAL];  /* value stack */

/* push: push f onto value stack */
void push(double f)
{
    if (sp < MAXVAL)
        val[sp++] = f;
    else
        printf("error: stack full, can't push %g\n", f);
}

/* pop: pop and return top value from stack */
double pop(void)
{
    if (sp > 0)
        return val[--sp];
    else 
	{
        printf("error: stack empty\n");
        return 0.0;
    }
}

/* push: push f onto value stack */
void view_stack()
{
	int i=sp;
    if (sp >0)
	{
       while(i>0)
	   {
		   printf("view_stack:%8g\n",val[i-1]);
		   i=i-1;
	   }
		
	}
    else
        printf("view_stack:Stack is empty\n");
}

/**********************************************************/
void showTop(void)
{
    if(sp > 0)
        printf("Top of stack contains: %8g\n", val[sp-1]);
    else
        printf("The stack is empty!\n");
}


void duplicate(void)
{
    double temp = 0.0;	
    if((sp > 0) &&(sp < MAXVAL))
    {
        temp = pop();
        push(temp);
        push(temp);				
	}
    else
        printf("The stack is empty!\n");	

}

void swapItems(void)
{
    double item1 = 0.0;
    double item2 = 0.0;	
    if(sp >= 2)
    {
        item1 = pop();
        item2 = pop();

        push(item1);
        push(item2);			
	}
    else
        printf("The stack is empty!\n");	
}

/* pop only returns a value if sp is greater than zero. So setting the
stack pointer to zero will cause pop to return its error */

void clearStack(void)
{
    sp = 0;
}

/**********************************************************/




#include <ctype.h>
int getch(void);
void ungetch(int);

/* getop: get next character or numeric operand */
int getop(char s[])
{
    int i, c;
    char setVar = FALSE;
    i = 0;
    while ((s[0] = c = getch()) == ' ' || c == '\t');
    s[1] = '\0';
    if (!isdigit(c) && !isalpha(c) && c != '.' && c != '-')
	{	
        return c; /* not a number */
	}

    if (c >= 'a' && c <= 'z')
    {
	    last_recent=c;
/* get next char and check if it was an equal symbol.*/ 		
        if ((s[++i] = c = getch()) == '=')
		{			
            setVar = TRUE;
			c = getch();
			s[++i] = c;		
		}
        else
        {
		    if (c != EOF)
	        {		
                   ungetch(c);
	        }
            return GETVARIABLE;
        }
    }

	if(c == '-')
	{		
        c = getch();	
        s[++i] = c;			
	}
	
    if (isdigit(c)) /* collect integer part */
	{	
        while (isdigit(s[++i] = c = getch()));
	}
    if (c == '.') /* collect fraction part */
	{	
        while (isdigit(s[++i] = c = getch()));
	}
    s[i] = '\0';
    if (c != EOF)
	{		
        ungetch(c);
	}
/* if s[0] == '-' && s[1] == '\0', return minus operator */	
    if (i == 1 && s[0] == '-') 
        return '-';	
    if (setVar)
	{	
        return SETVARIABLE;	
	}		
    return NUMBER;
}


#define BUFSIZE 100

char buf[BUFSIZE];   /* buffer for ungetch */
int bufp = 0;        /* next free position in buf */

int getch(void)      /* get a (possibly pushed-back) character */
{
    return (bufp > 0) ? buf[--bufp] : getchar();
}

void ungetch(int c) /* push character back on input */
{
    if (bufp >= BUFSIZE)
        printf("ungetch: too many characters\n");
    else
        buf[bufp++] = c;
}

      E x c e r c i s e 4 − 7 Excercise\quad 4-7 Excercise47

#include <stdio.h>
#include <stdlib.h> 
#include <ctype.h>
#include <math.h>
#include <string.h> 

#define MAXOP     100     /* max size of operand or operator */
#define NUMBER    '0'     /* signal that a number was found */
#define SETVARIABLE 's'   /* signal that a variable is being assigned */
#define GETVARIABLE 'g'   /* signal that a variable is being retrieved */
#define NUMVARS 26        /* number of variables supported (a-z) */

enum boolean {FALSE, TRUE};


int getop(char []);
void push(double);
double pop(void);
void showTop(void);
void duplicate(void);
void swapItems(void);
void clearStack();
void view_stack();	


/* initially as space such that malformed use of '=' won't cause segfaults */
char last_recent = ' '; 
/* array to store the double values for variables. 
Supports variables a through z (lower case). Initial value is 0*/
double varVals[NUMVARS] = {0.0}; 

/* reverse Polish calculator */
int main()
{
    int type;
    double op2;
    char s[MAXOP];
    while ((type = getop(s)) != EOF) 
	{
        switch (type) 
		{
            case NUMBER:
                 push(atof(s));
                 break;
/****************************************************/				 
            case SETVARIABLE:
                 if (strlen(s) > 2 && s[1] == '=')
                 {
                     int v = s[0];           /* stores variable */
                     int i = 1;              /* start at 1 since while loop needed ++i for a few reasons */
                     while (s[++i] != '\0')  /* this removes the variable name= part of s e.g. if s == "a=123.45" after loop s == "123.45" */
                         s[i - 2] = s[i];    /* shifts chars two to the left by 2 */
                     s[i - 2] = '\0';        /* since '\0' isn't copied, terminate string manually */
                     varVals[v - 'a'] = atof(s); /* convert string to double and store it in array */
                 }
                 else
                     printf("error: set variable length too small or incorrectly formatted (%s)\n", s);
                 break;
            case GETVARIABLE:
                 push(varVals[s[0] - 'a']);  /* convert the variable name to stored value */
                 break;	
/****************************************************/				 
            case '+':
                 push(pop() + pop());
                 break;
            case '*':
                 push(pop() * pop());
                 break;
            case '-':
                 op2 = pop();
                 push(pop() - op2);
                 break;
            case '/':
                 op2 = pop();
                 if (op2 != 0.0)
                     push(pop() / op2);
                 else
                     printf("error: zero divisor\n");
                 break;
            case '%':
                 op2 = pop();
                 if (op2 != 0.0)
                     push(fmod(pop(),op2));
                 else
                     printf("error: zero divisor\n");
                 break;
/****************************************************/				 
            case '?':
                showTop();
                break;
            case '#':
                duplicate();
                break;
            case '~':
                swapItems();
                break;
            case '!':
                clearStack();	
                break;				
/****************************************************/
			 
            case '$':
                push(sin(pop()));
                break;
            case '@':
                push(exp(pop()));
                break;
            case '^':
                op2 = pop();
                push(pow(pop(),op2));
                break;									
            // case '\n':
                 // printf("\t%.8g\n", pop());
                 // break;
            case '\n':
                 view_stack();
                 break;	
            case '_':
                 printf("The last recently used variable is %c=%8g\n",last_recent, varVals[last_recent-'a']);
                 break;					 
            default:
                 printf("error: unknown command %s\n", s);
                 break;
        }
    }
    return 0;
}

#define MAXVAL 100   /* maximum depth of val stack */
int sp = 0;          /* next free stack position */
double val[MAXVAL];  /* value stack */

/* push: push f onto value stack */
void push(double f)
{
    if (sp < MAXVAL)
        val[sp++] = f;
    else
        printf("error: stack full, can't push %g\n", f);
}

/* pop: pop and return top value from stack */
double pop(void)
{
    if (sp > 0)
        return val[--sp];
    else 
	{
        printf("error: stack empty\n");
        return 0.0;
    }
}

/* push: push f onto value stack */
void view_stack()
{
	int i=sp;
    if (sp >0)
	{
       while(i>0)
	   {
		   printf("view_stack:%8g\n",val[i-1]);
		   i=i-1;
	   }
		
	}
    else
        printf("view_stack:Stack is empty\n");
}

/**********************************************************/
void showTop(void)
{
    if(sp > 0)
        printf("Top of stack contains: %8g\n", val[sp-1]);
    else
        printf("The stack is empty!\n");
}


void duplicate(void)
{
    double temp = 0.0;	
    if((sp > 0) &&(sp < MAXVAL))
    {
        temp = pop();
        push(temp);
        push(temp);				
	}
    else
        printf("The stack is empty!\n");	

}

void swapItems(void)
{
    double item1 = 0.0;
    double item2 = 0.0;	
    if(sp >= 2)
    {
        item1 = pop();
        item2 = pop();

        push(item1);
        push(item2);			
	}
    else
        printf("The stack is empty!\n");	
}

/* pop only returns a value if sp is greater than zero. So setting the
stack pointer to zero will cause pop to return its error */

void clearStack(void)
{
    sp = 0;
}

/**********************************************************/




#include <ctype.h>
int getch(void);
void ungetch(int);

/* getop: get next character or numeric operand */
int getop(char s[])
{
    int i, c;
    char setVar = FALSE;
    i = 0;
    while ((s[0] = c = getch()) == ' ' || c == '\t');
    s[1] = '\0';
    if (!isdigit(c) && !isalpha(c) && c != '.' && c != '-')
	{	
        return c; /* not a number */
	}

    if (c >= 'a' && c <= 'z')
    {
	    last_recent=c;
/* get next char and check if it was an equal symbol.*/ 		
        if ((s[++i] = c = getch()) == '=')
		{			
            setVar = TRUE;
			c = getch();
			s[++i] = c;		
		}
        else
        {
		    if (c != EOF)
	        {		
                   ungetch(c);
	        }
            return GETVARIABLE;
        }
    }

	if(c == '-')
	{		
        c = getch();	
        s[++i] = c;			
	}
	
    if (isdigit(c)) /* collect integer part */
	{	
        while (isdigit(s[++i] = c = getch()));
	}
    if (c == '.') /* collect fraction part */
	{	
        while (isdigit(s[++i] = c = getch()));
	}
    s[i] = '\0';
    if (c != EOF)
	{		
        ungetch(c);
	}
/* if s[0] == '-' && s[1] == '\0', return minus operator */	
    if (i == 1 && s[0] == '-') 
        return '-';	
    if (setVar)
	{	
        return SETVARIABLE;	
	}		
    return NUMBER;
}


#define BUFSIZE 100

char buf[BUFSIZE];   /* buffer for ungetch */
int bufp = 0;        /* next free position in buf */

int getch(void)      /* get a (possibly pushed-back) character */
{
    return (bufp > 0) ? buf[--bufp] : getchar();
}

void ungetch(int c) /* push character back on input */
{
    if (bufp >= BUFSIZE)
        printf("ungetch: too many characters\n");
    else
        buf[bufp++] = c;
}

/*
   ungets() actually takes a little bit of thought.  Should the
   first character in "s" be sent to ungetch() first, or should
   it be sent last?  I assumed that most code calling getch()
   would be of this form:

     char array[...];
     int i;   

     while (...) {
       array[i++] = getch();
     }                  

   In such cases, the same code might call ungets() as:

     ungets(array);

   and expect to repeat the while loop to get the same string
   back.  This requires that the last character be sent first
   to ungetch() first, because getch() and ungetch() work with 
   a stack.     

   To answer K&R2's additional question for this problem,
   it's usually preferable for something like ungets() to just
   build itself on top of ungetch().  This allows us to change 
   ungetch() and getch() in the future, perhaps to use a linked 
   list instead, without affecting ungets().
*/ 
void ungets(const char *s)
{    
	int i, len;
	len = strlen(s);
	if(BUFSIZE - bufp >= len)  // ungets() must do its own bounds checking
	{
		for(i = strlen(s) - 1; i >= 0; i--)
			ungetch(s[i]);
	}
	else
		printf("error: insufficient space in buffer, can't execute ungets()\n");
}

      E x c e r c i s e 4 − 8 Excercise\quad 4-8 Excercise48

#include <stdio.h>
#include <stdlib.h> 
#include <ctype.h>
#include <math.h>
#include <string.h> 

#define MAXOP     100     /* max size of operand or operator */
#define NUMBER    '0'     /* signal that a number was found */
#define SETVARIABLE 's'   /* signal that a variable is being assigned */
#define GETVARIABLE 'g'   /* signal that a variable is being retrieved */
#define NUMVARS 26        /* number of variables supported (a-z) */

enum boolean {FALSE, TRUE};


int getop(char []);
void push(double);
double pop(void);
void showTop(void);
void duplicate(void);
void swapItems(void);
void clearStack();
void view_stack();	


/* initially as space such that malformed use of '=' won't cause segfaults */
char last_recent = ' '; 
/* array to store the double values for variables. 
Supports variables a through z (lower case). Initial value is 0*/
double varVals[NUMVARS] = {0.0}; 

/* reverse Polish calculator */
int main()
{
    int type;
    double op2;
    char s[MAXOP];
    while ((type = getop(s)) != EOF) 
	{
        switch (type) 
		{
            case NUMBER:
                 push(atof(s));
                 break;
/****************************************************/				 
            case SETVARIABLE:
                 if (strlen(s) > 2 && s[1] == '=')
                 {
                     int v = s[0];           /* stores variable */
                     int i = 1;              /* start at 1 since while loop needed ++i for a few reasons */
                     while (s[++i] != '\0')  /* this removes the variable name= part of s e.g. if s == "a=123.45" after loop s == "123.45" */
                         s[i - 2] = s[i];    /* shifts chars two to the left by 2 */
                     s[i - 2] = '\0';        /* since '\0' isn't copied, terminate string manually */
                     varVals[v - 'a'] = atof(s); /* convert string to double and store it in array */
                 }
                 else
                     printf("error: set variable length too small or incorrectly formatted (%s)\n", s);
                 break;
            case GETVARIABLE:
                 push(varVals[s[0] - 'a']);  /* convert the variable name to stored value */
                 break;	
/****************************************************/				 
            case '+':
                 push(pop() + pop());
                 break;
            case '*':
                 push(pop() * pop());
                 break;
            case '-':
                 op2 = pop();
                 push(pop() - op2);
                 break;
            case '/':
                 op2 = pop();
                 if (op2 != 0.0)
                     push(pop() / op2);
                 else
                     printf("error: zero divisor\n");
                 break;
            case '%':
                 op2 = pop();
                 if (op2 != 0.0)
                     push(fmod(pop(),op2));
                 else
                     printf("error: zero divisor\n");
                 break;
/****************************************************/				 
            case '?':
                showTop();
                break;
            case '#':
                duplicate();
                break;
            case '~':
                swapItems();
                break;
            case '!':
                clearStack();	
                break;				
/****************************************************/
			 
            case '$':
                push(sin(pop()));
                break;
            case '@':
                push(exp(pop()));
                break;
            case '^':
                op2 = pop();
                push(pow(pop(),op2));
                break;									
            // case '\n':
                 // printf("\t%.8g\n", pop());
                 // break;
            case '\n':
                 view_stack();
                 break;	
            case '_':
                 printf("The last recently used variable is %c=%8g\n",last_recent, varVals[last_recent-'a']);
                 break;					 
            default:
                 printf("error: unknown command %s\n", s);
                 break;
        }
    }
    return 0;
}

#define MAXVAL 100   /* maximum depth of val stack */
int sp = 0;          /* next free stack position */
double val[MAXVAL];  /* value stack */

/* push: push f onto value stack */
void push(double f)
{
    if (sp < MAXVAL)
        val[sp++] = f;
    else
        printf("error: stack full, can't push %g\n", f);
}

/* pop: pop and return top value from stack */
double pop(void)
{
    if (sp > 0)
        return val[--sp];
    else 
	{
        printf("error: stack empty\n");
        return 0.0;
    }
}

/* push: push f onto value stack */
void view_stack()
{
	int i=sp;
    if (sp >0)
	{
       while(i>0)
	   {
		   printf("view_stack:%8g\n",val[i-1]);
		   i=i-1;
	   }
		
	}
    else
        printf("view_stack:Stack is empty\n");
}

/**********************************************************/
void showTop(void)
{
    if(sp > 0)
        printf("Top of stack contains: %8g\n", val[sp-1]);
    else
        printf("The stack is empty!\n");
}


void duplicate(void)
{
    double temp = 0.0;	
    if((sp > 0) &&(sp < MAXVAL))
    {
        temp = pop();
        push(temp);
        push(temp);				
	}
    else
        printf("The stack is empty!\n");	

}

void swapItems(void)
{
    double item1 = 0.0;
    double item2 = 0.0;	
    if(sp >= 2)
    {
        item1 = pop();
        item2 = pop();

        push(item1);
        push(item2);			
	}
    else
        printf("The stack is empty!\n");	
}

/* pop only returns a value if sp is greater than zero. So setting the
stack pointer to zero will cause pop to return its error */

void clearStack(void)
{
    sp = 0;
}

/**********************************************************/




#include <ctype.h>
int getch(void);
void ungetch(int);

/* getop: get next character or numeric operand */
int getop(char s[])
{
    int i, c;
    char setVar = FALSE;
    i = 0;
    while ((s[0] = c = getch()) == ' ' || c == '\t');
    s[1] = '\0';
    if (!isdigit(c) && !isalpha(c) && c != '.' && c != '-')
	{	
        return c; /* not a number */
	}

    if (c >= 'a' && c <= 'z')
    {
	    last_recent=c;
/* get next char and check if it was an equal symbol.*/ 		
        if ((s[++i] = c = getch()) == '=')
		{			
            setVar = TRUE;
			c = getch();
			s[++i] = c;		
		}
        else
        {
		    if (c != EOF)
	        {		
                   ungetch(c);
	        }
            return GETVARIABLE;
        }
    }

	if(c == '-')
	{		
        c = getch();	
        s[++i] = c;			
	}
	
    if (isdigit(c)) /* collect integer part */
	{	
        while (isdigit(s[++i] = c = getch()));
	}
    if (c == '.') /* collect fraction part */
	{	
        while (isdigit(s[++i] = c = getch()));
	}
    s[i] = '\0';
    if (c != EOF)
	{		
        ungetch(c);
	}
/* if s[0] == '-' && s[1] == '\0', return minus operator */	
    if (i == 1 && s[0] == '-') 
        return '-';	
    if (setVar)
	{	
        return SETVARIABLE;	
	}		
    return NUMBER;
}


char buf=EOF;   /* buffer for ungetch */

int getch(void)      /* get a (possibly pushed-back) character */
{
    return (buf!=EOF) ? buf : getchar();
}

void ungetch(int c) /* push character back on input */
{
    if (buf!=EOF)
        printf("ungetch: too many characters\n");
    else
        buf = c;
}

      E x c e r c i s e 4 − 9 Excercise\quad 4-9 Excercise49

      E x c e r c i s e 4 − 10 Excercise\quad 4-10 Excercise410

#include <stdio.h>
#include <stdlib.h> 
#include <ctype.h>
#include <math.h>
#include <string.h> 

#define MAXOP     100     /* max size of operand or operator */
#define NUMBER    '0'     /* signal that a number was found */
#define SETVARIABLE 's'   /* signal that a variable is being assigned */
#define GETVARIABLE 'g'   /* signal that a variable is being retrieved */
#define NUMVARS 26        /* number of variables supported (a-z) */
#define MAXLINE 1000        /* number of variables supported (a-z) */

enum boolean {FALSE, TRUE};


int getop(char []);
void push(double);
double pop(void);
void showTop(void);
void duplicate(void);
void swapItems(void);
void clearStack();
void view_stack();	
int getline(char s[], int lim);

/* initially as space such that malformed use of '=' won't cause segfaults */
char last_recent = ' '; 
/* array to store the double values for variables. 
Supports variables a through z (lower case). Initial value is 0*/
double varVals[NUMVARS] = {0.0}; 

/*********************************/
char line[MAXLINE];
int line_i;
/*********************************/
/* reverse Polish calculator */
int main()
{
    int type;
    double op2;
    char s[MAXOP];
	
    while (getline(line, MAXLINE) != 0)
    {
    	line_i=0;
        while ((type = getop(s)) != '\0') 
    	{
            switch (type) 
    		{
                case NUMBER:
                     push(atof(s));
                     break;
    /****************************************************/				 
                case SETVARIABLE:
                     if (strlen(s) > 2 && s[1] == '=')
                     {
                         int v = s[0];           /* stores variable */
                         int i = 1;              /* start at 1 since while loop needed ++i for a few reasons */
                         while (s[++i] != '\0')  /* this removes the variable name= part of s e.g. if s == "a=123.45" after loop s == "123.45" */
                             s[i - 2] = s[i];    /* shifts chars two to the left by 2 */
                         s[i - 2] = '\0';        /* since '\0' isn't copied, terminate string manually */
                         varVals[v - 'a'] = atof(s); /* convert string to double and store it in array */
                     }
                     else
                         printf("error: set variable length too small or incorrectly formatted (%s)\n", s);
                     break;
                case GETVARIABLE:
                     push(varVals[s[0] - 'a']);  /* convert the variable name to stored value */
                     break;	
    /****************************************************/				 
                case '+':
                     push(pop() + pop());
                     break;
                case '*':
                     push(pop() * pop());
                     break;
                case '-':
                     op2 = pop();
                     push(pop() - op2);
                     break;
                case '/':
                     op2 = pop();
                     if (op2 != 0.0)
                         push(pop() / op2);
                     else
                         printf("error: zero divisor\n");
                     break;
                case '%':
                     op2 = pop();
                     if (op2 != 0.0)
                         push(fmod(pop(),op2));
                     else
                         printf("error: zero divisor\n");
                     break;
    /****************************************************/				 
                case '?':
                    showTop();
                    break;
                case '#':
                    duplicate();
                    break;
                case '~':
                    swapItems();
                    break;
                case '!':
                    clearStack();	
                    break;				
    /****************************************************/
    			 
                case '$':
                    push(sin(pop()));
                    break;
                case '@':
                    push(exp(pop()));
                    break;
                case '^':
                    op2 = pop();
                    push(pow(pop(),op2));
                    break;									
                // case '\n':
                     // printf("\t%.8g\n", pop());
                     // break;
                case '\n':
                     view_stack();
                     break;	
                case '_':
                     printf("The last recently used variable is %c=%8g\n",last_recent, varVals[last_recent-'a']);
                     break;					 
                default:
                     printf("error: unknown command %s\n", s);
                     break;
            }
        }
    }
    return 0;
}

#define MAXVAL 100   /* maximum depth of val stack */
int sp = 0;          /* next free stack position */
double val[MAXVAL];  /* value stack */

/* push: push f onto value stack */
void push(double f)
{
    if (sp < MAXVAL)
        val[sp++] = f;
    else
        printf("error: stack full, can't push %g\n", f);
}

/* pop: pop and return top value from stack */
double pop(void)
{
    if (sp > 0)
        return val[--sp];
    else 
	{
        printf("error: stack empty\n");
        return 0.0;
    }
}

/* push: push f onto value stack */
void view_stack()
{
	int i=sp;
    if (sp >0)
	{
       while(i>0)
	   {
		   printf("view_stack:%8g\n",val[i-1]);
		   i=i-1;
	   }
		
	}
    else
        printf("view_stack:Stack is empty\n");
}

/**********************************************************/
void showTop(void)
{
    if(sp > 0)
        printf("Top of stack contains: %8g\n", val[sp-1]);
    else
        printf("The stack is empty!\n");
}


void duplicate(void)
{
    double temp = 0.0;	
    if((sp > 0) &&(sp < MAXVAL))
    {
        temp = pop();
        push(temp);
        push(temp);				
	}
    else
        printf("The stack is empty!\n");	

}

void swapItems(void)
{
    double item1 = 0.0;
    double item2 = 0.0;	
    if(sp >= 2)
    {
        item1 = pop();
        item2 = pop();

        push(item1);
        push(item2);			
	}
    else
        printf("The stack is empty!\n");	
}

/* pop only returns a value if sp is greater than zero. So setting the
stack pointer to zero will cause pop to return its error */

void clearStack(void)
{
    sp = 0;
}

/**********************************************************/




#include <ctype.h>
int getch(void);
void ungetch(int);

/* getop: get next character or numeric operand */
int getop(char s[])
{
    int i, c;
    char setVar = FALSE;
    i = 0;
    while ((s[0] = c = line[line_i++]) == ' ' || c == '\t');
    s[1] = '\0';
    if (!isdigit(c) && !isalpha(c) && c != '.' && c != '-')
	{	
        return c; /* not a number */
	}

    if (c >= 'a' && c <= 'z')
    {
	    last_recent=c;
/* get next char and check if it was an equal symbol.*/ 		
        if ((s[++i] = c = line[line_i++]) == '=')
		{			
            setVar = TRUE;
			c = line[line_i++];
			s[++i] = c;		
		}
        else
        {
		    if (c != '\0')
	        {		
                line_i=line_i-1;
	        }
            return GETVARIABLE;
        }
    }

	if(c == '-')
	{		
        c = line[line_i++];	
        s[++i] = c;			
	}
	
    if (isdigit(c)) /* collect integer part */
	{	
        while (isdigit(s[++i] = c = line[line_i++]));
	}
    if (c == '.') /* collect fraction part */
	{	
        while (isdigit(s[++i] = c = line[line_i++]));
	}
    s[i] = '\0';
    if (c != '\0')
	{		
        line_i=line_i-1;
	}
/* if s[0] == '-' && s[1] == '\0', return minus operator */	
    if (i == 1 && s[0] == '-') 
        return '-';	
    if (setVar)
	{	
        return SETVARIABLE;	
	}		
    return NUMBER;
}


// /* getop: get next character or numeric operand */
// int getop(char s[])
// {
    // int i, c;
    // char setVar = FALSE;
    // i = 0;
    // while ((s[0] = c = getch()) == ' ' || c == '\t');
    // s[1] = '\0';
    // if (!isdigit(c) && !isalpha(c) && c != '.' && c != '-')
	// {	
        // return c; /* not a number */
	// }

    // if (c >= 'a' && c <= 'z')
    // {
	    // last_recent=c;
// /* get next char and check if it was an equal symbol.*/ 		
        // if ((s[++i] = c = getch()) == '=')
		// {			
            // setVar = TRUE;
			// c = getch();
			// s[++i] = c;		
		// }
        // else
        // {
		    // if (c != EOF)
	        // {		
                   // ungetch(c);
	        // }
            // return GETVARIABLE;
        // }
    // }

	// if(c == '-')
	// {		
        // c = getch();	
        // s[++i] = c;			
	// }
	
    // if (isdigit(c)) /* collect integer part */
	// {	
        // while (isdigit(s[++i] = c = getch()));
	// }
    // if (c == '.') /* collect fraction part */
	// {	
        // while (isdigit(s[++i] = c = getch()));
	// }
    // s[i] = '\0';
    // if (c != EOF)
	// {		
        // ungetch(c);
	// }
// /* if s[0] == '-' && s[1] == '\0', return minus operator */	
    // if (i == 1 && s[0] == '-') 
        // return '-';	
    // if (setVar)
	// {	
        // return SETVARIABLE;	
	// }		
    // return NUMBER;
// }

/* getline:  get line into s, return length */
int getline(char s[], int lim)
{
    int c, i;

    i = 0;
    while (--lim > 0 && (c = getchar()) != EOF && c != '\n')
        s[i++] = c;
    if (c == '\n')
        s[i++] = c;
    s[i] = '\0';

    return i;
}

      E x c e r c i s e 4 − 11 Excercise\quad 4-11 Excercise411

#include <stdio.h>
#include <stdlib.h> 
#include <ctype.h>
#include <math.h>
#include <string.h> 

#define MAXOP     100     /* max size of operand or operator */
#define NUMBER    '0'     /* signal that a number was found */
#define SETVARIABLE 's'   /* signal that a variable is being assigned */
#define GETVARIABLE 'g'   /* signal that a variable is being retrieved */
#define NUMVARS 26        /* number of variables supported (a-z) */

enum boolean {FALSE, TRUE};


int getop(char []);
void push(double);
double pop(void);
void showTop(void);
void duplicate(void);
void swapItems(void);
void clearStack();
void view_stack();	


/* initially as space such that malformed use of '=' won't cause segfaults */
char last_recent = ' '; 
/* array to store the double values for variables. 
Supports variables a through z (lower case). Initial value is 0*/
double varVals[NUMVARS] = {0.0}; 

/* reverse Polish calculator */
int main()
{
    int type;
    double op2;
    char s[MAXOP];
    while ((type = getop(s)) != EOF) 
	{
        switch (type) 
		{
		
            case NUMBER:
                 push(atof(s));
                 break;
/****************************************************/				 
            case SETVARIABLE:
                 if (strlen(s) > 2 && s[1] == '=')
                 {
                     int v = s[0];           /* stores variable */
                     int i = 1;              /* start at 1 since while loop needed ++i for a few reasons */
                     while (s[++i] != '\0')  /* this removes the variable name= part of s e.g. if s == "a=123.45" after loop s == "123.45" */
                         s[i - 2] = s[i];    /* shifts chars two to the left by 2 */
                     s[i - 2] = '\0';        /* since '\0' isn't copied, terminate string manually */
                     varVals[v - 'a'] = atof(s); /* convert string to double and store it in array */
                 }
                 else
                     printf("error: set variable length too small or incorrectly formatted (%s)\n", s);
                 break;
            case GETVARIABLE:
                 push(varVals[s[0] - 'a']);  /* convert the variable name to stored value */
                 break;	
/****************************************************/				 
            case '+':
                 push(pop() + pop());
                 break;
            case '*':
                 push(pop() * pop());
                 break;
            case '-':
                 op2 = pop();
                 push(pop() - op2);
                 break;
            case '/':
                 op2 = pop();
                 if (op2 != 0.0)
                     push(pop() / op2);
                 else
                     printf("error: zero divisor\n");
                 break;
            case '%':
                 op2 = pop();
                 if (op2 != 0.0)
                     push(fmod(pop(),op2));
                 else
                     printf("error: zero divisor\n");
                 break;
/****************************************************/				 
            case '?':
                showTop();
                break;
            case '#':
                duplicate();
                break;
            case '~':
                swapItems();
                break;
            case '!':
                clearStack();	
                break;				
/****************************************************/
			 
            case '$':
                push(sin(pop()));
                break;
            case '@':
                push(exp(pop()));
                break;
            case '^':
                op2 = pop();
                push(pow(pop(),op2));
                break;									
            // case '\n':
                 // printf("\t%.8g\n", pop());
                 // break;
            case '\n':
                 view_stack();
                 break;	
            case '_':
                 printf("The last recently used variable is %c=%8g\n",last_recent, varVals[last_recent-'a']);
                 break;					 
            default:
                 printf("error: unknown command %s\n", s);
                 break;
        }
    }
    return 0;
}

#define MAXVAL 100   /* maximum depth of val stack */
int sp = 0;          /* next free stack position */
double val[MAXVAL];  /* value stack */

/* push: push f onto value stack */
void push(double f)
{
    if (sp < MAXVAL)
        val[sp++] = f;
    else
        printf("error: stack full, can't push %g\n", f);
}

/* pop: pop and return top value from stack */
double pop(void)
{
    if (sp > 0)
        return val[--sp];
    else 
	{
        printf("error: stack empty\n");
        return 0.0;
    }
}

/* push: push f onto value stack */
void view_stack()
{
	int i=sp;
    if (sp >0)
	{
       while(i>0)
	   {
		   printf("view_stack:%8g\n",val[i-1]);
		   i=i-1;
	   }
		
	}
    else
        printf("view_stack:Stack is empty\n");
}

/**********************************************************/
void showTop(void)
{
    if(sp > 0)
        printf("Top of stack contains: %8g\n", val[sp-1]);
    else
        printf("The stack is empty!\n");
}


void duplicate(void)
{
    double temp = 0.0;	
    if((sp > 0) &&(sp < MAXVAL))
    {
        temp = pop();
        push(temp);
        push(temp);				
	}
    else
        printf("The stack is empty!\n");	

}

void swapItems(void)
{
    double item1 = 0.0;
    double item2 = 0.0;	
    if(sp >= 2)
    {
        item1 = pop();
        item2 = pop();

        push(item1);
        push(item2);			
	}
    else
        printf("The stack is empty!\n");	
}

/* pop only returns a value if sp is greater than zero. So setting the
stack pointer to zero will cause pop to return its error */

void clearStack(void)
{
    sp = 0;
}

/**********************************************************/




#include <ctype.h>

/* getop: get next character or numeric operand */
int getop(char s[])
{
    int i;
    static int c=EOF;	
    static int unget_flag=0;		
    char setVar = FALSE;
    i = 0;
	if(unget_flag==1)
	{
		if((c== ' ') || (c == '\t'))
	    {
            while ((s[0] = c = getchar()) == ' ' || c == '\t');	    		    	
	    }	
		else
		{
			s[0] = c;			
		}
		unget_flag=0;
	}
	else
	{
        while ((s[0] = c = getchar()) == ' ' || c == '\t');				
	}

    s[1] = '\0';
    if (!isdigit(c) && !isalpha(c) && c != '.' && c != '-')
	{	
        return c; /* not a number */
	}

    if (c >= 'a' && c <= 'z')
    {
	    last_recent=c;
/* get next char and check if it was an equal symbol.*/ 		
        if ((s[++i] = c = getchar()) == '=')
		{			
            setVar = TRUE;
			c = getchar();
			s[++i] = c;		
		}
        else
        {
			if (c != EOF)
	        {		
                unget_flag=1;
	        }			
            return GETVARIABLE;
        }
    }

	if(c == '-')
	{		
        c = getchar();	
        s[++i] = c;			
	}
	
    if (isdigit(c)) /* collect integer part */
	{	
        while (isdigit(s[++i] = c = getchar()));
	}
    if (c == '.') /* collect fraction part */
	{	
        while (isdigit(s[++i] = c = getchar()));
	}	
    s[i] = '\0';
    if (c != EOF)
	{		
        unget_flag=1;
	}		
/* if s[0] == '-' && s[1] == '\0', return minus operator */	
    if (i == 1 && s[0] == '-') 
        return '-';	
    if (setVar)
	{	
        return SETVARIABLE;	
	}		
    return NUMBER;
}

      E x c e r c i s e 4 − 12 Excercise\quad 4-12 Excercise412

#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include <string.h>

void itoa_myself(int n, char s[], int minmum);

int main(void) 
{
    char buffer[100];
    
    printf("INT_MIN: %d\n", INT_MIN);
    itoa_myself(INT_MIN, buffer,25);
    printf("Buffer : %s\n", buffer);
    printf("\\*******************************\\\n");   
    printf("378\n");
    itoa_myself(378, buffer,25);
    printf("Buffer : %s\n", buffer);
    printf("\\*******************************\\\n");   
    printf("-873\n");
    itoa_myself(-873, buffer,25);
    printf("Buffer : %s\n", buffer);
   
    return 0;
}

void itoa_myself(int n, char s[],int minmum) 
{
    static int i=0;
    static int recur_num=0;	
	recur_num=recur_num+1;
    if(n<0)
	{
        s[i++] = '-';		
	}
    if(n/10)
	{
		itoa_myself(abs(n/10), s,minmum); 
	} 
	s[i++] = abs(n % 10) + '0';	
    if(i>minmum)
	{
		printf("Elements overflow\n");
	}
	recur_num=recur_num-1;
	if(recur_num==0)
	{	
	    s[i] = '\0';	
        i=0;
        recur_num=0;	    		
	}
}

      E x c e r c i s e 4 − 13 Excercise\quad 4-13 Excercise413

#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include <string.h>

void itoa_myself(int n, char s[], int minmum);
void reverse(char s[]);

int main(void) 
{
    char buffer[100];
    
    printf("INT_MIN: %d\n", INT_MIN);
    itoa_myself(INT_MIN, buffer,25);
    printf("Buffer : %s\n", buffer);
    
    return 0;
}

void itoa_myself(int n, char s[], int minmum) 
{
    int i, sign;
    sign = n;
    
    i = 0;
    do 
	{
        s[i++] = abs(n % 10) + '0';
    } while ( n /= 10 );
    if (sign < 0)
        s[i++] = '-';
	while(i<minmum)
	{
        s[i++] = ' ';		
	}	
    s[i] = '\0';
    reverse(s);
}

void reverse(char s[]) 
{
    int c;	
    static int first_flag=1;		
    static int i=0;	
    static int j=0;
	if(first_flag==1)
	{
		first_flag=0;
		j=strlen(s)-1;
	}
	
    if ( i < j ) 
	{
        c = s[i];
        s[i] = s[j];
        s[j] = c;
		i=i+1;
		j=j-1;
		reverse(s);
    }
}

      E x c e r c i s e 4 − 14 Excercise\quad 4-14 Excercise414

#include <stdio.h>

#define swap(t,x,y) {              \
	                    t temp=x;  \
                        x=y;       \
					    y=temp;    \
					}

int main(void) 
{
    int a=6;
	int b=9;
	swap(int,a,b)
    printf("a=%d,b=%d\n", a,b);
    return 0;
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1613277.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【Linux驱动层】iTOP-RK3568学习之路(四):杂项设备驱动框架

一、杂项设备驱动简介 在 Linux 中&#xff0c;把无法归类的五花八门的设备定义成杂项设备。相较于字符设备&#xff0c;杂项设备有以下两个优点: (1)节省主设备号:杂项设备的主设备号固定为 10&#xff0c;而字符设备不管是动态分配还是静态分配设备号&#xff0c;都会消耗一…

AlDente Pro for mac最新激活版:电池长续航软件

AlDente Pro是一款专为Mac用户设计的电池管理工具&#xff0c;旨在提供电池安全和健康管理的一站式解决方案。它具备实时监控电池状态的功能&#xff0c;让用户随时了解电池的电量、充电次数、健康状态等信息。 AlDente Pro for mac最新激活版下载 同时&#xff0c;AlDente Pro…

【蓝桥杯2025备赛】集合求和

集合求和 题目描述 给定一个集合 s s s&#xff08;集合元素数量 ≤ 30 \le 30 ≤30&#xff09;&#xff0c;求出此集合所有子集元素之和。 输入格式 集合中的元素&#xff08;元素 ≤ 1000 \le 1000 ≤1000&#xff09; 输出格式 s s s 所有子集元素之和。 样例 #1 …

Docker搭建项目管理软件禅道

文章目录 一、简介二、部署三、使用 一、简介 禅道是以项目管理为核心的协作平台&#xff0c;旨在帮助团队高效地进行项目管理和协作。 禅道提供了项目管理、任务管理、团队协作、文档管理、报告统计等功能。 禅道官网 二、部署 操作系统&#xff1a;22.04.4 创建文件夹 …

ARM与单片机有啥区别?

初学者必知&#xff1a;ARM与单片机到底有啥区别&#xff1f;1、软件方面这应该是最大的区别了。引入了操作系统。为什么引入操作系统&#xff1f;有什么好处嘛&#xff1f; 在开始前我有一些资料&#xff0c;是我根据网友给的问题精心整理了一份「ARM的资料从专业入门到高级教…

【OpenHarmony-NDK技术】简单将cJson移植到OpenHarmony中,并在c层修改参数值再返回json

1、cJson的简单介绍 cJson - github网址 概述 一般使用cJson是&#xff0c;需要将json文本转化为json对象–编码&#xff0c;将json对象转化为json文本–解析。 git clone https://github.com/DaveGamble/cJSON.git 后留意cJSON.h和cJSON.h两个文件。 1、cJson的介绍 cJso…

使用FPGA实现比较器

介绍 比较器就是通过比较输入的大小&#xff0c;然后输出给出判断。 在这个比较器中&#xff0c;有两个输入&#xff0c;三个输出。根据输出就可以判断出哪个输入值大了。 设计文件 library ieee; use ieee.std_logic_1164.all; use ieee.std_logic_arith.all; entity compa…

JAVA----Thread

Thread 这里写目录标题 Thread线程Thread 第 1 种写法此外, t.start()的作用 Thread 第 2 种写法Thread 第 3 种写法Thread 第 4 种写法Thread 第 5 种写法 线程 本身是操作系统提供的, 操作系统提供了 API 以让我们操作线程, JVM 就对操作系统 API 进行了封装. 线程这里, 则提…

verilog变量类型wire、reg和Memory的介绍和用法

目录 wire型 reg型 Memory型 wire型 wire 类型变量&#xff0c;也叫网络类型变量&#xff0c;用于结构实体之间的物理连接&#xff0c;如门与门之间&#xff0c;不能储存值&#xff0c;用连续赋值语句 assign 赋值&#xff0c;定义为 wire [n-1:0] a ; 其中 n 代表位宽&…

OCT2Former: A retinal OCT-angiography vessel segmentationtransformer论文总结

论文(COMPUT METH PROG BIO)&#xff1a;OCT2Former: A retinal OCT-angiography vessel segmentation transformer 源码&#xff1a;https://github.com/coreeey/OCT2Former 一、摘要 背景与目的&#xff1a;视网膜血管分割在视网膜疾病自动筛查与诊断中起着重要作用。如何分…

面试高频:HTTPS 通信流程

更多大厂面试内容可见 -> http://11come.cn 面试高频&#xff1a;HTTPS 通信流程 HTTPS 的加密流程 接下来说一下 HTTPS 协议是如何进行通信的&#xff1a; HTTPS 通信使用的 对称加密 非对称加密 两者结合的算法 HTTPS 通信时&#xff0c;会先使用 非对称加密 让通信双…

大sql mysql执行

先把sql 拆分 太大的执行失败 使用 SQLDumpSplitter3 拆分sql 执行拆分的sql 拆分的sql 打开发现很多 ; 开头的空行 替换掉 正则 ^; 修改数据库 my.cnf my,ini 执行可能会提示 [ERR] 2006 - Server has gone away 错误 在 [mysqld] 添加以下几行 wait_timeout2880000 inter…

Qt基础之四十六:Qt界面中嵌入第三方程序的一点心得

本文主要讲解QWidget和QWindow的区别,以及如何在QWidget中嵌入第三方程序,并完美解决在QWidget中嵌入某些程序(比如Qt程序)时出现的白边问题。 下面是嵌入QQ音乐的样子,这首歌还不错。 先用spy++查看QQ音乐的窗口信息,如果安装了Visual Studio,工具菜单里自带spy++ 然后…

【1471】java项目进度管理系统Myeclipse开发mysql数据库web结构java编程计算机网页项目

一、源码特点 java 项目进度管理系统是一套完善的java web信息管理系统&#xff0c;对理解JSP java编程开发语言有帮助&#xff0c;系统具有完整的源代码和数据库&#xff0c;系统主要采用B/S模式开发。开发环境为TOMCAT7.0,Myeclipse8.5开发&#xff0c;数据库为Mysql5.0&…

【Linux】自定义协议——实现网络序列化和反序列化

欢迎来到Cefler的博客&#x1f601; &#x1f54c;博客主页&#xff1a;折纸花满衣 &#x1f3e0;个人专栏&#xff1a;题目解析 &#x1f30e;推荐文章&#xff1a;承接上文内容【Linux】应用层协议序列化和反序列化 目录 &#x1f449;&#x1f3fb;代码实现如下Calculate.hp…

企业常用Linux三剑客awk及案例/awk底层剖析/淘宝网cdn缓存对象分级存储策略案例/磁盘知识/awk统计与计算-7055字

高薪思维&#xff1a; 不愿意做的事情:加班&#xff0c;先例自己在利他 生活中先利他人在利自己 感恩&#xff0c;假设别人帮助过你&#xff0c;先帮助别人&#xff0c;感恩境界 awk三剑客老大 find其实也算是一种新的第四剑客 find 查找文件 查找文件&#xff0c;与其他命令…

【UnityShader】图片圆角

1.需求 我们在开发的时候&#xff0c;有时候一些按钮或者菜单栏的边角是直角的需要改成圆角&#xff0c;但是让美术重新绘制耽误时间不说也确实没必要&#xff0c;这个时候我们不妨使用一个简单的shader去解决这个问题&#xff0c;下面我们就讲讲这个shader要如何实现。 需求1…

设计模式之观察者模式(优先使用对象组合的原则)的C++实现

观察者模式又称订阅者发布者模式&#xff0c;本篇介绍主要是利用对象组合大于类继承的设计模式原则实现订阅发布模式&#xff0c;这种设计的优点是想订阅数据的类不需要继承订阅者类的抽象类&#xff0c;减少了一层类的继承&#xff1b;当然&#xff0c;具体情况需要可根据需求…

在ios设备上运行Unity Profiler

久违了朋友们。 最近基于Unity 2021.3 和AR Foundation开发了个应用&#xff0c;需要在ipad上实际运行时查看程序的各项指标功耗。 于是乎&#xff0c;我尝试跟随者官方教程来实时调试&#xff0c;现在附上一些心得。 按照官方的三步走&#xff0c;Build and Run理论上会自动…

42岁TVB男艺人曾靠刘德华贴钱出道,苦熬10年终上位

张颕康在无线&#xff08;TVB&#xff09;电视打滚多年&#xff0c;近年在《逆天奇案》第一、二辑凭扎实演技为人留下印象。他还是圈中出名的「爱妻号」&#xff0c;日前在访问期间&#xff0c;张颕康三句不离多谢太太。 较年长的观众或会记得&#xff0c;张颕康初出道以「刘德…