Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   C++ Calculator (http://www.go4expert.com/forums/cpp-calculator-t14795/)

Dak914 26Oct2008 06:33

C++ Calculator
 
I have just begun programming in C++, coming into it from Java. I have noticed that making a calculator that doesnt crash is, in a sense, hard for any newbie beginner. For all the other newbie beginners like me, I have developed a simple and relatively easy to understand calculator. It doesnt use any graphics, just a terminal. Before you continue, one of the included files, called sstream, uses something called stringstream to convert data from a string to a int, double, float, ect. This is what I am using to prevent the program from crashing, so if you input anything other than a number or operator, you will get a numberE+number or the number 0. This is a relatively large script because I wanted to make it easy to understand. I know I could have used more comments. Well, finally, here is that code.

fix: Uh, nevermind, I am not completely sure on how I get the code into the post so you can just download it from here...

http://dak914.t35.com/calc.cpp

This site will be dedicated to my source code files from now on...Just in case you were wondering... :happy:

Learn.
~Connor

xpi0t0s 26Oct2008 15:17

Re: C++ Calculator
 
Use [ code ] and [ /code ] (without the spaces). For example, entering
[ code ]
double calc (string a, string oper, string b)
{
double c;
double d;
double answer;
[ /code ]

gives the result:
Code:

double calc (string a, string oper, string b)
 {
 double c;
 double d;
 double answer;


shabbir 26Oct2008 15:25

Re: C++ Calculator
 
http://www.go4expert.com/misc.php?do=bbcode#code should also help

xpi0t0s 26Oct2008 15:26

Re: C++ Calculator
 
calc() can be streamlined quite a lot, for example, if oper is char (not char*) rather than string:
Code:

switch (oper)
{
case '+': return c+d;
case '-': return c-d;
default: return 0;
}

It's not necessary to assign the result of a calculation to a variable whose only purpose is to return that value; you can juse use return <expr>;

In terms of improving the program, there's not much that else can be done within the existing functionality. It's very simple, the only improvements really can be the addition of new features: other operators, functions, memory/memories etc. Have a look at Windows Calc for other inspiration.

Dak914 26Oct2008 19:52

Re: C++ Calculator
 
Oh, I get it now. Well thanks a ton. Like I said I am new to C++. I am currently working on the card game called War. I read up a little more on the switch thing. I am going to use my website for all my code so you can download it and view it in your own preferred environment, such as notepad or Visual C++. Thanks again for the tips
~Connor


All times are GMT +5.5. The time now is 14:20.