Public Group

# Please check this for me. :)

This topic is 2109 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

How would you use functions in a calculator program?
I got the jumping into c++ book and i've met functions again. This time, i kinda understand it (this is the 5th book i'm using to learn c++), last problem was vectors so i decided i needed a new book (this was after 2 failed functions learning and 1 failed array learning).
In this book, functions comes before arrays and the first time i met functions was in the cplusplus.com pdf, then in programming principles book which i just switched from and i had no idea what so ever what it did/what they were talking about, so i changed books. Now i've met it again and this book explains better.
I was writing calculator program and it doesn't seem right, it does everything right but it's like 2/3x more code than doing everything in
int main()

.

How would you use functions in a simple (+, -, /, *) calculator program?

My code is below.

Thanks.
#include <iostream>
#include <string>

double calc_add (double a, double B)/>
{
return a+b;
}

double calc_minus(double a, double B)/>
{
return a-b;
}

double calc_multiply(double a, double B)/>
{
return a*b;
}

double calc_divide(double a, double B)/>
{
return a/b;
}

void calculator ()
{

double x = 0;
double y = 0;
char unit = ' ';
std::string QUIT;

do
{

std::cout <<"CALCULATOR \n\n";

std::cout <<"Enter operation: ";
std::cin >> x >> unit >> y;

switch (unit)
{
case '+':
break;

case '-':
std::cout << calc_minus(x, y);
break;

case '*':
std::cout << calc_multiply(x, y);
break;

case '/':
std::cout << calc_divide(x,y);
break;

}

std::cout << "\n\nDo you want to quit: ";
std::cin >> QUIT;

if (QUIT == "No")
{
system ("cls")
)

}

while (QUIT == "No");
}

int main()
{
calculator();

return 0;
}

No indentation (no tab key on mobile).

##### Share on other sites

Checked.

Does not compile.

---

EDIT: I see you've updated your post, so I'll reply to that as well.

Once the compile errors and such are fixed, the application does what I expect it to.

While in this specific case it might be more tedious and more lines of code to use functions instead of just having everything inside main, I expect the example is meant to teach you several things, including:

A) How functions are declared/defined.

B) How functions are called.

C) How functions parameters work.

D) How code can be split out of 1 huge function to create several smaller & more managable ones (Refactoring).

Edited by CoreLactose

##### Share on other sites

How would you use functions in a simple (+, -, /, *) calculator program?

I would not use functions, just a switch in a loop and directly using those math operators...

Checked.

Does not compile.

if (QUIT == "No")
{
system ("cls")
)

}

Edited by Alessio1989

##### Share on other sites
Indentifying it for you...

#include <iostream>
#include <string>

double calc_add (double a, double B)/>
{
return a+b;
}

double calc_minus(double a, double B)/>
{
return a-b;
}

double calc_multiply(double a, double B)/>
{
return a*b;
}

double calc_divide(double a, double B)/>
{
return a/b;
}

void calculator ()
{

double x = 0;
double y = 0;
char unit = ' ';
std::string QUIT;

do
{

std::cout <<"CALCULATOR \n\n";

std::cout <<"Enter operation: ";
std::cin >> x >> unit >> y;

switch (unit)
{
case '+':
break;

case '-':
std::cout << calc_minus(x, y);
break;

case '*':
std::cout << calc_multiply(x, y);
break;

case '/':
std::cout << calc_divide(x,y);
break;

}

std::cout << "\n\nDo you want to quit: ";
std::cin >> QUIT;

if (QUIT == "No")
{
system ("cls")
)

}

while (QUIT == "No");
}

int main()
{
calculator();

return 0;
}

...it becomes apparent that you forgot a closing } after the calculator() function (hence the indent level of main()). This is why indentation is good, and if mobiles don't let you indent when posting then God help us all. (But that's a different discussion.)

Typically, for a calculator program most people aren't going to use this kind of structure. It's just not very useful or flexible. For example, how would you deal with parentheses? With multiple operations?

In order to deal with the full range of possibilities of a calculator, you need to have a bit more complex paradigm. At the simplest, you'll probably want to implement a simple stack-based lexer and parser. This will convert the input expression to a stream of tokens (lexical analysis) then construct a syntax tree on the stack that can then be evaluated to generate the result. This will allow you to deal with any level of parenthetical nesting and any kind of complex expression, as long as it is well-formed. (And you can test for syntax errors during parsing to catch the malformed expressions).

Typically too, all of this (lexing, parsing, evaluation) will be encapsulated into their own modules, whether by C style functions, by C++ class, whatever. They will be quite separate from all of the input and output facilities you provide, rather than all tied up together. A sample structure might be (pseudocode)

while (running)
Obtain input string
Pass input string to lexer to obtain a token stream
Pass the token stream to parser to obtain a syntax tree (stack)
Pass the stack to the evaluator to obtain the result
Display the result
Wanna quit? yes/no

You can see how in the simple pseudocode there are clearly delineated sections? Each of those sections can be implemented as a separate module. Lexer/parsing/evaluation stuff is an excellent example of black-box design, where each component or module accepts some input and returns some output, no side-effects, no persistent state or any complexity. Just simple input/output. Makes it very easy to separate into discrete tasks.

##### Share on other sites
The code (the one in my pc compiles). I posted via phone so there is no way to indent or check errors.

What kind of program will use functions, i need something to practice on.
Thanks.

##### Share on other sites

I was writing calculator program and it doesn't seem right, it does everything right but it's like 2/3x more code than doing everything in main()

In this case, the program's overall complexity is probably just at the point where there is little to be gained by moving the math to independent functions. Imagine that your next task is implementing a scientific calculator, which might have ten times the number of operations - main() would become very long, difficult to read and debug.

There are other benefits too. Without trying to go into too much detail, as this is probably a bit beyond where you are now, but there are advanced techniques available where the code in main() could be reduced considerably by moving from a giant switch statement to having an array of key, function pointer pairs - main becomes a little loop to find the appropriate entry in the array and call whatever function is relevant.

This is the nature of textbooks, due to space constraints it is difficult to include complex examples that might merit using more advanced techniques, not to mention the daunting task of introducing complex examples in a way that adds to understanding rather than creates confusion.

##### Share on other sites

The code (the one in my pc compiles). I posted via phone so there is no way to indent or check errors.

What kind of program will use functions, i need something to practice on.
Thanks.

Literally an infinite amount of programs will use functions.

For testing purposed, I know several books have functions for e.g.:

- Compute the circumference of a circle, given radius as input.

- Compute the area of a circle, given radius as input.

- Compute the radius of a circle, given the area or circumference as input.

- Compute the volume of a sphere, given the radius as input.

- Store the users name (input) and print (output) a box of asterisks (*) large enough to fit the name + some padding.

- Print a ASCII triangle with the height determined by the user's input.

- Figure out the distance between 2 points, given 2 or 3 coordinates per point (2 for 2D distance, 3 for 3D distance).

- Write a function that takes a non-zero integer as input which computes the factorial of that input. Don't worry if it doesn't work for huge numbers where the result would exceed what a float/int can store. Stuff like that is more advanced.

- Create a function to output a sting using alternate UPPERCASE and lowercase.

##### Share on other sites

The goal of functions is to break up larger groups of logic into smaller, self contained groups of logic.  In your case, you are breaking up mathematical operations.  While it is true that this produces more code, it *usually* makes programs easier to maintain.  Since I have seen you post a lot about game engines, I will use an example relating to a game engine.  You don't write a game engine entirely in the entry point -- to do so would be stupid, long, and it I can almost guarantee the code would not be maintainable (or is some cases usable).  On top of that, there are some special use cases were you would need functions.  Take for example a "collision check" function which returns a Boolean value -- "true" if there is collision, "false" if there is no collision.  Because of the functions nature, it could be called 1000+ times per-frame.  If you don't use functions, you would have to type the same code over and over again, versus calling a self contained function that takes two objects and returns a Boolean value.

Addressing the code snippets you have posted and the fact that they do not compile.

First, you mention "C++."  What you are programming in there is the beginner "hybrid mix."  The way you are declaring functions is C-style syntax, but you are including C++ standard headers and using C++ data types (std::string).  While not an issue, it is a pet peeve of mine.  Second, after each function declaration you have "/>."  I am not sure if that is something your phone added, or if you coded that, but "/>" is not valid C or C++ syntax.  Third, C++ is CASE SENSITIVE.  In the parameter list of the functions you declare "B" as uppercase, but when you use it in the method, you use "b."  Finally, while not a problem, it annoys me a little.  The way you handle input is off.  You print out instructions once, and then have the user input three numbers, two of which have no instructions as to what they are.  If I didn't know this was a calculator, I would be staring at the screen, scratching my head.

Happy coding,

~ Byte.

EDIT: One more thing -- "Quit" generally referrers to the program exiting.  "system( "cls" )" clears the screen.

Edited by ByteTroll

##### Share on other sites

The goal of functions is to break up larger groups of logic into smaller, self contained groups of logic.  In your case, you are breaking up mathematical operations.  While it is true that this produces more code, it *usually* makes programs easier to maintain.  Since I have seen you post a lot about game engines, I will use an example relating to a game engine.  You don't write a game engine entirely in the entry point -- to do so would be stupid, long, and it I can almost guarantee the code would not be maintainable (or is some cases usable).  On top of that, there are some special use cases were you would need functions.  Take for example a "collision check" function which returns a Boolean value -- "true" if there is collision, "false" if there is no collision.  Because of the functions nature, it could be called 1000+ times per-frame.  If you don't use functions, you would have to type the same code over and over again, versus calling a self contained function that takes two objects and returns a Boolean value.

Addressing the code snippets you have posted and the fact that they do not compile.

First, you mention "C++."  What you are programming in there is the beginner "hybrid mix."  The way you are declaring functions is C-style syntax, but you are including C++ standard headers and using C++ data types (std::string).  While not an issue, it is a pet peeve of mine.  Second, after each function declaration you have "/>."  I am not sure if that is something your phone added, or if you coded that, but "/>" is not valid C or C++ syntax.  Third, C++ is CASE SENSITIVE.  In the parameter list of the functions you declare "B" as uppercase, but when you use it in the method, you use "b."  Finally, while not a problem, it annoys me a little.  The way you handle input is off.  You print out instructions once, and then have the user input three numbers, two of which have no instructions as to what they are.  If I didn't know this was a calculator, I would be staring at the screen, scratching my head.

Happy coding,
~ Byte.

EDIT: One more thing -- "Quit" generally referrers to the program exiting.  "system( "cls" )" clears the screen.

Um, what do you mean by i declare functions c style. I haven't learnt c so could you compare my code with a pure c++ code.
I know c++ is case sensitive, the phone thinks it's a smiley and changes it from b to B and adds /> everytime i edit the post.
What's wrong with my input?

##### Share on other sites

If you leanr C++ you learn C too because c++ inherits from c as language. He mean with c style exactly what he wrote:

First, you mention "C++."  What you are programming in there is the beginner "hybrid mix."  The way you are declaring functions is C-style syntax, but you are including C++ standard headers and using C++ data types (std::string).  While not an issue, it is a pet peeve of mine

• ### Game Developer Survey

We are looking for qualified game developers to participate in a 10-minute online survey. Qualified participants will be offered a \$15 incentive for your time and insights. Click here to start!

• 9
• 11
• 15
• 21
• 26