> Problems with c++ code from website.?

Problems with c++ code from website.?

Posted at: 2014-12-18 
There are two separate issues here. The computation is easy. Either use a for loop or a recursive call. The for loop is faster in pretty much every language that has both possibilities, but computer scientists are in love with recursion.

long result = 1;

for (int i=2; i<=n; ++i) { result *= i; }

The part I can't show you is how to add ! as an operator. I've done it in my own calculator (started out as C in the early '90s, now is C++ with arbitrary precision arithmetic) but I don't know what parsing strategy Stroustrup used nor why the ding-dong he is presenting a parser in a book he claims is "aimed at beginners taking a programming course."

If that's pasted out of his book, he's got the two problems tangled up in the problem statement, like he's deliberately trying to make it harder.

Somewhere, there's a grammatical definition of a factor, maybe already layered a bit to handle other unary operators like + or - without a left operand.

::=

|| -

|| +

If that's something like it, replace with and write:

::=

|| !

That's descriptive, not practical BNF. Top-down parsers will have trouble with left recursion. Bottom up parsers will have trouble with right recursion. An "extended BNF" is usually used to handle these situations without recursion. (Once again, recursion loses in practice. But my parser was top-down recursive--with those mods to avoid recursions that don't consume a token--so don't think that I consider recursion evil!)

Your code to perform the factorial computation will placed in or called by the code that recognizes that ! is a valid construction, much the same way as - is handed. Take a look at how unary - is handled by the existing code, and use that as a general guide.

ok. I am using the book, "Programming: Principles and Practice Using C++". I am on chapter 6 and trying to do the drills. I will list his site below so you can download the code. I have fixed all the code errors. Now I am on drill 4. It says, "Add a factorial operator: use a suffix ! operator to represent “factorial.” For example, the expression 7! means 7 * 6 * 5 * 4 * 3 * 2 * 1. Make ! bind tighter than * and /; that is, 7*8! means 7*(8!) rather than (7*8)!. Begin by modifying the grammar to account for a higher-level operator. To agree with the standard mathematical definition of factorial, let 0! evaluate to 1. Hint: The calculator functions deal with doubles, but factorial is defined only for ints, so just for x!, assign the x to an int and calculate the factorial of that int." You will have to look at the full code to help me figure out this problem. Basically, it loads a char and a number(as double) into a var caalled token.What I can't figure out isto do the math on a variable located in a different token string. Look at the code if you have any questions, it is very well commented.

Here is the website:

http://www.stroustrup.com/Programming/