The C Programming Language 练习题4-5

题目
给计算器程序增加访问sin、exp 与pow 等库函数的操作。有关这些库函数的详细信息,参见附录B.4节中的头文件

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

#define MAXOP 100
#define NUMBER '0'
#define MAXVAL 100 /* maximum depth of val stack */
#define NAME 'a'

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


int main()
{
    int type, i;
    double op2;
    char s[MAXOP], matchcmd[MAXOP];

    i = 0;
    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 '%':
            push((int)pop() % (int)pop());
            break;
        case '\n':
            printf("\t%.8g\n", pop());
            break;
        case NAME:
            mathfnc(s);
            break;
        default:
            printf("error: unknown command %s\n", matchcmd);
            break;
        }
    }
    return 0;
}

void mathfnc(char matchcmd[])
{
    double op4, op5;

    if(!strcmp(matchcmd, "sin"))
        {
            op4 = sin(pop());
            push(op4);
        }
    else if (!strcmp(matchcmd, "exp"))
        {
            op4 = exp(pop());
            push(op4);
        }
    else if(!strcmp(matchcmd, "pow"))
        {
            op4 = pop();
            op4 = pow(pop(), op4);
            push(op4);
        }
    else
        printf("error: command unknown.");
}

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, d;

    while ((s[0] = c = getch()) == ' ' || c == '\t')
        ;
    s[1] = '\0';
    if (!isdigit(c) && c != '.' && c != '-' && !islower(c))
        return c;   /*not a number */
    if ((c == '-' || c == '+') && !isdigit(d = getch()))
        {
            ungetch(d);
            return c;
        }
    i = 0;
    if(islower(c))
        {
        while(islower(s[++i] = c = getch()))
            ;
        s[i] = '\0';
        if(c != EOF)
            ungetch(c);
        return NAME;
        }
    if (isdigit(c))/* a number without '+' and '-' */
        {
            while(isdigit(s[++i] = c = getch()))
        ;
        }
        else /* a number with '+' and '-' */
        {
            s[++i] = d;
            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);
    return NUMBER;
}

#define BUFSIZE 1000

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;
}
The C programming Language By Brian W. Kernighan and Dennis M. Ritchie. Published by Prentice-Hall in 1988 ISBN 0-13-110362-8 (paperback) ISBN 0-13-110370-9 目录结构: Contents Preface Preface to the first edition Introduction Chapter 1: A Tutorial Introduction Getting Started Variables and Arithmetic Expressions The for statement Symbolic Constants Character Input and Output File Copying Character Counting Line Counting Word Counting Arrays Functions Arguments - Call by Value Character Arrays External Variables and Scope Chapter 2: Types, Operators and Expressions Variable Names Data Types and Sizes Constants Declarations Arithmetic Operators Relational and Logical Operators Type Conversions Increment and Decrement Operators Bitwise Operators Assignment Operators and Expressions Conditional Expressions Precedence and Order of Evaluation Chapter 3: Control Flow Statements and Blocks If-Else Else-If Switch Loops - While and For Loops - Do-While Break and Continue Goto and labels Chapter 4: Functions and Program Structure Basics of Functions Functions Returning Non-integers External Variables Scope Rules Header Files Static Variables Register Variables Block Structure Initialization Recursion The C Preprocessor File Inclusion Macro Substitution Conditional Inclusion Chapter 5: Pointers and Arrays Pointers and Addresses Pointers and Function Arguments Pointers and Arrays Address Arithmetic Character Pointers and Functions Pointer Arrays; Pointers to Pointers Multi-dimensional Arrays Initialization of Pointer Arrays Pointers vs. Multi-dimensional Arrays Command-line Arguments Pointers to Functions Complicated Declarations Chapter 6: Structures Basics of Structures Structures and Functions Arrays of Structures Pointers to Structures Self-referential Structures Table Lookup Typedef Unions Bit-fields Chapter 7: Input and Output Standard Input and Output Formatted Output - printf Variable-length Argument Lists Formatted Input - Scanf File Access Error Handling - Stderr and Exit Line Input and Output Miscellaneous Functions String Operations Character Class Testing and Conversion Ungetc Command Execution Storage Management Mathematical Functions Random Number generation Chapter 8: The UNIX System Interface File Descriptors Low Level I/O - Read and Write Open, Creat, Close, Unlink Random Access - Lseek Example - An implementation of Fopen and Getc Example - Listing Directories Example - A Storage Allocator Appendix A: Reference Manual Introduction Lexical Conventions Syntax Notation Meaning of Identifiers Objects and Lvalues Conversions Expressions Declarations Statements External Declarations Scope and Linkage Preprocessor Grammar Appendix B: Standard Library Input and Output: <stdio.h> File Operations Formatted Output Formatted Input Character Input and Output Functions Direct Input and Output Functions File Positioning Functions Error Functions Character Class Tests: <ctype.h> String Functions: <string.h> Mathematical Functions: <math.h> Utility Functions: <stdlib.h> Diagnostics: <assert.h> Variable Argument Lists: <stdarg.h> Non-local Jumps: <setjmp.h> Signals: <signal.h> Date and Time Functions: <time.h> Implementation-defined Limits: <limits.h> and <float.h> Appendix C: Summary of Changes
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值