Stroustrup的C ++ Book练习

时间:2015-05-16 18:17:25

标签: c++

我从Stroustrup的书中学习C ++:编程:使用C ++的原理与实践。我正在第6章,我们正在编写一个计算器,现在:

  

我必须添加一个因子条款,其出价高于*/。在原始程序中,我们有3个级别primary(浮点文字和括号),terms(*和/)和expressions(+或 - )。   expression做的是致电term,收集左手边等等。为了实现阶乘,我在fact()term之间添加了primary(),以便将其投标更严格。   在添加fact()之前,计算器工作正常。然后我添加了fact以便从primary获取数据,而term现在正在从fact获取数据。

现在回答问题:

Q1:正如我已经说过的,在添加fact之前一切都很好。现在唯一正确的输出方程是term。当我尝试做其他算术时,它只打印我最后输入的数字。我在哪里弄乱了其他操作。

Q2 :(有点偏离主题)为什么当我尝试退出程序时(输入'q',我需要三到四次输入'q'才能退出。

以下是代码:

#include "std_lib_facilities.h"


class Token {
public:
    char kind;        // what kind of token
    double value;     // for numbers: a value
    Token(char ch)    // make a Token from a char
        :kind(ch), value(0) { }
    Token(char ch, double val)     // make a Token from a char and a double
        :kind(ch), value(val) { }
};

//------------------------------------------------------------------------------

class Token_stream {
public:
    Token_stream();         // make a Token_stream that reads from cin
    Token get();            // get a Token
    void putback(Token t);  // put a Token back
private:
    bool full;      // is there a Token in the buffer
    Token buffer;   // here is where we keep a Token put back using putback();
};

// Constructor
Token_stream::Token_stream()
    :full(false),buffer(0)
{
}

Token_stream ts;

void Token_stream::putback(Token t)
{
    if (full)  error("putback() into a full buffer"); // checks if we're using putback() twice
    buffer = t;  // copy t to buffer
    full = true; // buffer is now full
}

Token Token_stream::get()
{
    if (full) {     // do we already have a Token ready?
                // remove Token from buffer
        full = false;
        return buffer;
    }

    char ch;
    cin >> ch; // note that >> skips whitespace

    switch(ch) {
    case ';':   // for "print"
    case 'q':   // for "quit"
    case '(': case ')': case '{': case '}': case '!': case'+': case '-': case'/': case '*':
        return Token(ch);  // let each character represent itself
    case '.':
    case '0': case '1': case '2': case '3': case '4':
    case '5': case '6': case '7': case '8': case '9':
    {
        cin.putback(ch);        // put digit back into the input stream
        double val;
        cin >> val;
        return Token('8',val);  // let '8' represent a "number"
        break;
    }
    default:
        error("Bad token");
        return 0;
    }
}



Token get_token()    // read a token from cin
{
    char ch;
    cin >> ch;    // note that >> skips whitespace (space, newline, tab, etc.)

    switch (ch) {

    case 'q':
    case ';':
    case '(': case ')': case '{': case '}': case '!': case '+': case '-': case '*': case '/':
        return Token(ch);        // let each character represent itself
    case '.':
    case '0': case '1': case '2': case '3': case '4':
    case '5': case '6': case '7': case '8': case '9':
        {
            cin.putback(ch);         // put digit back into the input stream
            double val;
            cin >> val;              // read a floating-point number
            return Token('8',val);   // let '8' represent "a number"
        }
    default:
        error("Bad token");
        return 0;
    }
}

//------------------------------------------------------------------------------

double expression();  // read and evaluate a Expression

//------------------------------------------------------------------------------

double term();        // read and evaluate a Term

//------------------------------------------------------------------------------

double primary()
{
    Token t = ts.get();
    switch (t.kind) {
    case '(':    // handle '(' expression ')'
        {
            double d = expression();
            t = ts.get();
            if (t.kind != ')') error("')' expected");
            return d;
        }
    case '{':    // handle '(' expression ')'
            {
                double d = expression();
                t = ts.get();
                if (t.kind != '}') error("'}' expected");
                return d;
            }
    case '8':            // we use '8' to represent a number
        return t.value;  // return the number's value
    default:
        return 0;
        error("primary expected");
    }
}

//------------------------------------------------------------------------------

int main()
try {
        double val = 0;
        while(cin)
        {
            Token t = ts.get();

            if(t.kind == 'q') break; //'q' for quit
            if(t.kind == ';')
                cout << "=" << val << "\n";
            else
                ts.putback(t);
            val = expression();
        }

    keep_window_open("q");
}
catch (exception& e) {
    cerr << e.what() << endl;
    keep_window_open ("q");
    return 1;
}
catch (...) {
    cerr << "exception \n";
    keep_window_open ("q");
    return 2;
}

//------------------------------------------------------------------------------

double expression()
{
    double left = term();      // read and evaluate a Term
    Token t = ts.get();        // get the next token

    while(true) {
        switch(t.kind) {
        case '+':
            left += term();    // evaluate Term and add
            t = ts.get();
            break;
        case '-':
            left -= term();    // evaluate Term and subtract
            t = ts.get();
            break;
        default:
            ts.putback(t);
            return left;       // finally: no more + or -: return the answer
        }
    }
}

//------------------------------------------------------------------------------

double factorial(double val)
{
    double res=1;
    for(int i=1; i<=val; i++)
        res *= i;
    return res;
}

double fact()
{
    double left = primary();
    Token t = ts.get();

    switch(t.kind)
    {
    case '!':
        {   double res = factorial(left);
            return res;
        }
    default:
        return left;
    }
}

//------------------------------------------------------------------------------

double term()
{
    double left = fact();
    Token t = ts.get();     // get the next token

    while(true) {
        switch (t.kind) {
        case '*':
            left *= fact();
            t = ts.get();
            break;
        case '/':
            {
                double d = fact();
                if (d == 0) error("divide by zero");
                left /= d;
                t = ts.get();
                break;
            }
        default:
            ts.putback(t);
            return left;
        }
    }
}

很抱歉,如果我不够具体。 这是我第一次发布这样的帖子。

1 个答案:

答案 0 :(得分:2)

从第二个问题开始:

您需要多次按q几次作为参数:

keep_window_open("q");

因此,每次退出while循环时,它都会等待您输入q以关闭控制台。

关于您的阶乘函数:

指定您的计算器语法:编写现有操作的优先顺序,即调用顺序包含它们的函数。这将使您更容易合并新功能。

最好将factorial作为附加case添加到primary()中,因为括号具有比 term()中的乘法,除法等。

以下是一种可能的实施方式:

double primary(){
    Token t = ts.get();
    switch (t.kind) {
    case '{':{
        double d = expression();
        t = ts.get();
        if (t.kind != '}') error("'}' expected");
        return d;
    }
    case '(':    // handles '(' expression ')'{    
        double d = expression();
        t = ts.get();
        if (t.kind != ')') error("')' expected");
        return d;
    }
    case '8': case '!':{
        // include a test whether the number is integer and > 0 
        if(is_factorial()){
            double d  = factorial(t.value);
            t = ts.get();
            return d;
        }
        else return t.value;
    }
    default:
        error("primary expected");
    }
}

其中:

/*
   Non-member method: factorial.
   Use: double fact = factorial(double);
   This funnction provides factorial operator.
*/
double factorial(double num){
   if(num <= 1) return 1;
   return num*factorial(num-1);
}

/*
   Non-member method: is_factorial.
   Use: bool fact = is_factorial(void);
   This funnction returns true if a number
   is followed by factorial opertor. 
   Used as an indicator to call factorial function.
*/
bool is_factorial(){
    Token t = ts.get();
    if (t.kind == '!'){
        ts.putback(t);
        return true;
    }
    ts.putback(t);
    return false;
}