gpt4 book ai didi

c++ - Stroustrup 的 C++ 书籍练习

转载 作者:太空狗 更新时间:2023-10-29 21:40:49 25 4
gpt4 key购买 nike

我正在从 Stroustrup 的书中学习 C++:Programming: Principles and Practice using C++。我在第 6 章,我们正在编写一个计算器,现在:

I have to add a factorial clause which bids stronger than * and /. In the original program we had 3 levels, primary (floating point literals & parentheses), terms (* and /) and expressions (+ or -). What expression does is call term, to collect its left hand side and so on. In order to implement the factorial I've added a fact() between termand primary(), in order to bid it tighter. Before adding fact() the calculator was working perfectly fine. Then I added fact in order to take data from primary and term is now taking data from 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;
}
}
}

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

最佳答案

从你的第二个问题开始:

你需要按 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;
}

关于c++ - Stroustrup 的 C++ 书籍练习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30279162/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com