PDA

View Full Version : [OT] Nobby and his noob Calculator made in C++ - advice needed



nobby
03-03-09, 15:32
Hello there,

One of my assaignments for Programming, was to create a calculator,

This is what i've done:

#include <iostream.h>
#include <stdlib.h>

int main()
{
int number1, // Declaration of viariables
number2,
continyou = 1;
float total;
char operation;
while (continyou == 1)
{
cout << "Please enter first number: "; //Output message for user to input First Number
cin >> number1;
cout << "Please enter the operation you would like to carry out (+ - * /)"; //Output message to allow user to select which mathmatical operation to use
cin >> operation;
if (operation = '+') //If the selected operation is +
{
cout << "Please enter the second number: ";
cin >> number2;
total = number1 + number2; //Calculates the two totals
cout << "Total = " << total; //Displays the finished calculation of two totals on screen
}

else if (operation = '-') //If the selected operation is -
{
cout << "Please enter a number to subtract: ";
cin >> number2;
total = number1 - number2; //Displays the finished calculation of two totals on screen
}
else if (operation = '*') //If the selected operation is *
{
cout << "Please enter a number to multiply: ";
cin >> number2;
total = number1 * number2; //Displays the finished calculation of two totals on screen
}
else if (operation = '/') //If the selected operation is /
{
cout << "Please enter a number to divide by.";
cin >> number2;
}
while (number2 == 0) //If the user attmpts to Divide by Zero, An error message is displayed to the user
{
cout << "You can not divide by zero. Please try again.";
cin >> number2;
}
cout << " The total is: " << total << endl; //Displays the finished calculation of two totals on screen
cout << "Want to go again? Press 1 to Continue! ";
cin >> continyou;
}
system("PAUSE");
return 0;
}


For some reason, when asked by my lecturer to input, it says that -7 divided by -2 = -9

The answer should be 3.5

Why does this happen?

Biglines
03-03-09, 15:38
maybe it doesn't convert a string -7 to numeric -7? i'm not into c++ myself, but can't find anything about that in ur code

also, it cud be it takes the - from the second number as the operator? (so saying -7 -2 = -9?)

rob444
03-03-09, 15:51
Am I blind or is there no division in the code at all? :P

Nidhogg
03-03-09, 16:01
There's a problem here:

if (operation = '+')

That = needs to be ==. The single = just sets the operation to '+', and -7 plus -2 = -9. :) The same applies to the other if statements.

N

P.S. Continyou is spelt continue (which of course you can't have because it's a keyword).

Jaffo
03-03-09, 16:36
There's a problem here:

if (operation = '+')

That = needs to be ==. The single = just sets the operation to '+', and -7 plus -2 = -9. :) The same applies to the other if statements.

N

P.S. Continyou is spelt continue (which of course you can't have because it's a keyword).

your so sexy

Nidhogg
03-03-09, 16:50
This thread just reminds of how much I hate C++. The best definition of the C++ language I ever heard was "C++ makes C bigger but the result is the same".

N

Kanedax
03-03-09, 16:50
I R A PRUGRAMMUR!

http://logic.stanford.edu/talks/conquest/programmer.jpeg

Chosen One
03-03-09, 17:53
I R A PRUGRAMMUR!

http://logic.stanford.edu/talks/conquest/programmer.jpeg

Kane, dont kid your self :lol:

http://i4.photobucket.com/albums/y141/fewa_geta/Alex%20Chelsea%20others/Random/computer-cat-3.jpg

Nidhogg
03-03-09, 18:39
Let's have less of the spam, eh?

N

Hell-demon
03-03-09, 18:52
I read that code and now I have a brain tumour.


Thanks, [ edited ]

silent000
03-03-09, 19:12
I dont do alot of coding in C++ any more but if you want an answer that is as you say '3.5' you either want to declare your variables as a 'decimal' or a floating point

EDIT: just saw that your 'total' variable is actually a float, try having 'number1' and 'number2' as a float aswell oh yes and as Niddy said the operator must be '==' instead of '='

Chosen One
03-03-09, 19:41
Let's have less of the spam, eh?

N

how about we have a spam forum.......... :D

vices
03-03-09, 19:52
Hmm, not sure but would a switch statement be better?

:)

Kanedax
03-03-09, 20:04
how about we have a spam forum.......... :D

I concur.

Hell-demon
03-03-09, 20:13
Can we Nid?



Pleeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeaaaaaaaase

Hoder
03-03-09, 20:21
Back on topic or I'll tell Nid where you all live.

silent000
03-03-09, 20:31
Hmm, not sure but would a switch statement be better?

:)

A switch and case statement is what I used for my calculator when they asked me to when I was at college, but in my experience depending on your lecturer they get rather shitty when you try and be all smart with them ;) It didn't go down too well when I spotted about ten mistakes in the lecturer's code :cool:

Deno
03-03-09, 23:20
You needed to set the numbers 1 and 2 as floating point values. Since they were integers, C++ rounded them before inputting them into the fTotal value, which was float, thus giving you the original rounded value instead of the floating value you required. Also as someone mentioned i think, you need to have the '==' contained in the "if/if else" statement.
As far as i could see the programme works now ;) enjoy

#include <iostream.h>
#include <stdlib.h>

int main()
{
float number1, // Declaration of viariables
number2,
continyou = 1;
float total;
char operation;
while (continyou == 1)
{
cout << "Please enter first number: "; //Output message for user to input First Number
cin >> number1;
cout << "Please enter the operation you would like to carry out (+ - * /)"; //Output message to allow user to select which mathmatical operation to use
cin >> operation;
if (operation == '+') //If the selected operation is +
{
cout << "Please enter the second number: ";
cin >> number2;
total = number1 + number2; //Calculates the two totals
cout << "Total = " << total; //Displays the finished calculation of two totals on screen
}

else if (operation == '-') //If the selected operation is -
{
cout << "Please enter a number to subtract: ";
cin >> number2;
total = number1 - number2; //Displays the finished calculation of two totals on screen
}
else if (operation == '*') //If the selected operation is *
{
cout << "Please enter a number to multiply: ";
cin >> number2;
total = number1 * number2; //Displays the finished calculation of two totals on screen
}
else if (operation == '/') //If the selected operation is /
{
cout << "Please enter a number to divide by.";
cin >> number2;
total = number1 / number2;
}

while (number2 == 0) //If the user attmpts to Divide by Zero, An error message is displayed to the user
{
cout << "Only Chuck Norris can divide by zero, fool! Please try again.";
cin >> number2;
}
cout << " The total is: " << total << endl; //Displays the finished calculation of two totals on screen
cout << "Want to go again? Press 1 to Continue! ";
cin >> continyou;
}
system("PAUSE");
return 0;
}

Brammers
03-03-09, 23:22
So who's going to re-code that using C# and Reflection? :D

Nidhogg
03-03-09, 23:30
So who's going to re-code that using C# and Reflection? :D
Don't talk to me about C# and reflection. I just wrote an algorithm that recursively travels a deeply nested object model, uses reflection to determine the type of each node and then calls a method delegate at runtime appropriate to that type in order to translate it into something else. Oh, and the model also contains generic collections of objects that also have to be travelled.

It was actually a lot of fun because I don't usually get to write code these days. :)

N

P.S. I didn't mention the integer operands because I figured they were intentional. The floating point result is only necessary to support the division operator. You could equally say that they should all be strings and then properly validated and casted because there are too many ways to break that program based on invalid user inputs.

Deno
03-03-09, 23:36
Yes, your right about the division, but its still useful to have all the values as floats so you can input non integer numbers. You ever tried using a calculator for a day using only whole number values? ;P

Also it might impress your lecturer if you include a system like your non zero division to stop users inputting invalid operators.

silent000
03-03-09, 23:46
So who's going to re-code that using C# and Reflection? :D

C# ... My Favorite language :) Ask me to write anything including your own girlfriend and i'll do it :cool:

Oh plus nobby you want to put a try catch in there for validation because if I had your application open in front of me I would just break it by doing 7 divided by 0 ;)

Biglines
03-03-09, 23:54
any particular reason for breaking it with 7/0? personally I'm a big fan of breaking things by doing 9/0...

Nidhogg
03-03-09, 23:58
Oh plus nobby you want to put a try catch in there for validation because if I had your application open in front of me I would just break it by doing 7 divided by 0 ;)
Lol, you should read his code again - that's the one thing he does look out for. :p

N

Neallys
04-03-09, 00:28
I thought using an other language but english was prohibited :p

Brammers
04-03-09, 00:33
C# ... My Favorite language :) Ask me to write anything including your own girlfriend and i'll do it :cool:


Which girlfriend would your like to #include in your code? :p

I've seen some comments in a file once, where a programmer made a small dedication in his comments to his girlfriend because he was working on a Saturday.

The next day there was a comment in response, to her seeing the comment in the code. Her response was "Is that it?"

I just hope he never told her compiled code doesn't leave the comments in!



Oh plus nobby you want to put a try catch in there for validation because if I had your application open in front of me I would just break it by doing 7 divided by 0 ;)

As Niddy said, he did test that in his code, give him a chance to get around to exception handling in C++, but please don't terrify him with the murky world of pointers. :p

Now a question/debate for the coders here, which would you use? An excpetion handler to trap Divide by zero or a if num==0 clause to prevent divide by zero error?

Nidhogg
04-03-09, 00:59
The "if" every time. Go investigate the cost of throwing exceptions versus a simple zero comparison. Exceptions are orders of magnitude more expensive and, as named, should only be used for exceptional purposes.

If you have complex maths that eventually cause a divide by zero that you couldn't predict then, fine, that's what exceptions are there for, but you shouldn't use them in place of simple input validation.

N

/edit - Also, related to exceptions...

Never use exceptions in place of explicit flow control
Never swallow exceptions you can't handle
Although exceptions are expensive, don't get carried away because everything's relative. If it makes sense to use an exception then use it, regardless of perceived cost. For example, you could argue that since the divide by zero in the example above would be exceptional it would be cheaper to trap it with an exception rather than executing a zero comparison on every input, but since there are going to be so few inputs in a program like that there's not really much difference. I'd still recommend the if in this case because it's pure input validation.
Be careful when porting from .NET 1.1 to .NET 2.0 with exceptions thrown in threads. Behaviour has changed, and code that would have happily run in .NET 1.1 will terminate in 2.0.

Transformer
04-03-09, 02:18
Dunno if I should let you in on my secret but....the easiest way to pass any C++ or programming class...google.

search "C++ Calculator" Bam....assignment done.

silent000
04-03-09, 10:30
Yes and the lecturer's are oblivious to the thing called the internet... Yes that'll work...

rob444
04-03-09, 12:49
Fuck this and go with lolcode instead. :/

Nidhogg
04-03-09, 13:40
In LOLCODE it would go something like this:

HAI
CAN HAS STDIO?
I HAS A NUMBAR1
I HAS A NUMBAR2
I HAS A CONTINYOU BTW SEE HOW I DIDNT HAF TO RENAME THS? LOL
I HAS A TOTL
I HAS A OPERASHUN


IM IN YR LOOP

VISIBLE "Please enter first NUMBAR: "
GIMMEH NUMBAR1

VISIBLE "Please enter the operation you would like to carry out (+ - * /)"
GIMMEH OPERASHUN

IZ OPERASHUN LIEK "+"?
YARLY
BTW If the selected operation is +
VISIBLE "Please enter the second NUMBAR: "
GIMMEH NUMBAR2
LOL TOTL R NUMBAR1 UPZ NUMBAR2
VISIBLE TOTL
NOWAI
IZ OPERATOR LIEK "-"?
YARLY
BTW If the selected operation is -
VISIBLE "Please enter the second NUMBAR: "
GIMMEH NUMBAR2
LOL TOTL R NUMBAR1 NERF NUMBAR2
VISIBLE TOTL
NOWAI
IZ OPERATOR LIEK "*"?
YARLY
BTW If the selected operation is *
VISIBLE "Please enter the second NUMBAR: "
GIMMEH NUMBAR2
LOL TOTL R NUMBAR1 TIEMZ NUMBAR2
VISIBLE TOTL
NOWAI
IZ OPERATOR LIEK "/"?
YARLY
BTW If the selected operation is /
VISIBLE "Please enter the second NUMBAR: "
GIMMEH NUMBAR2
PLZ LOL TOTL R NUMBAR1 OVAR NUMBAR2
AWSUM THX
VISIBLE TOTL
O NOES
VISIBLE "ACK!!1ONE - ZEROWS DUDE!"
KTHX
KTHX
KTHX
KTHX
KTHX

KTHXBYE

You can see that to satisfy the exception crowd I made use of the PLZ - AWSUM THX - ONOES exception handling mechanism to trap the divide by zero. ;)

rob444
04-03-09, 14:09
Nidhogg, you were just placed in a very special place in my heart. Be proud young padawan, be proud...

Biglines
04-03-09, 17:47
omfg... it's an actual language.. :D gotta love teh intarwebs

Zefrian
04-03-09, 18:20
funny ... i knew, that there are some strange programming languages like "brainfuck" or "chef" ... but never heared/read about "lolcode" up to now :D

Rambus
05-03-09, 20:10
To build a real calculator...

Please google 'Prefix notation'
This is required to handle order of operations / bracketing.
Once you have all your symbols in prefix notation, push them to a stack
Pop top, it will be a command. Pop LHS (if its not another command) it is a symbol, likewise for RHS. Once you have a symbol for LHS and RHS then perform the head command. Repeat until the stack has a single symbol- The answer!

-C++, but very C like implementation, I'm not 100% if it will compile as C code
-Also I didn't actually use a stack for this implementation.. But hey, It's about 4 years old..
-Proof of concept only, can easily be crashed



void expr();
void error();
void lex();
void term();
void exp();
void factor();
#include <string>
#include <iostream>
#include <vector>
#include <math.h>
#include <stdio.h>

#include "StringUtils.h"

using namespace std;
string inputString = "1 + ( 1 * 2 ) ^ 2";
vector<string> input;
int position = 0;

static int nextToken;
static int nextValue = 0;
static int result = 0;
enum codes
{
ID_CODE,
PLUS_CODE,
MINUS_CODE,
AST_CODE,
SLASH_CODE,
LEFT_PAREN_CODE,
RIGHT_PAREN_CODE,
EXP_CODE,
EndOfInput
};

int main()
{
printf("Expression: %s \n",inputString.c_str());
StringUtils::SplitString(inputString," ",input,false);
lex();
result = nextValue;
expr();
//Display Result
printf("Result: %i \n",result);
return 0;
}

void expr(void)
{
printf("Enter <expr>\n");
term();
while(nextToken == PLUS_CODE || nextToken == MINUS_CODE)
{
lex();
term();
result += nextValue;
}
printf("Exit <expr> \n");
}

void term()
{
printf("Enter <term>\n");
factor();
while(nextToken == AST_CODE || nextToken == SLASH_CODE)
{
char oldToken = nextToken;
int oldValue = nextValue;
lex();
factor();
if(oldToken == AST_CODE)
nextValue *= oldValue;
else
nextValue /= oldValue;
}
printf("Exit <term>\n");
}

void factor(void)
{
printf("Enter <factor> \n");
exp();
while(nextToken == EXP_CODE)
{
int oldValue = nextValue;
lex();
exp();
double tmp = pow((double)oldValue,(double)nextValue);
//To keep things clean, truncate the value into an int.
nextValue = (int)tmp;
}
printf("Exit <factor>\n");
}


void exp()
{
printf("Enter <exp>\n");
if(nextToken == ID_CODE)
lex();
else if( nextToken == LEFT_PAREN_CODE)
{
lex();
expr();
if(nextToken == RIGHT_PAREN_CODE)
lex();
else
error();
}
else
error();
printf("Exit <exp>\n");
}

void error()
{
printf( "\nInvalid: Error!\n" );
exit(0);
}
void lex()
{
if(input.size() == position)
{
nextToken = EndOfInput;
printf( "Call lex /* returns end-of-input */\n");
return;
}
//could be a switch statement if we use char's
if(input[position] == "*")
nextToken = AST_CODE;
else if (input[position] == "+")
nextToken = PLUS_CODE;
else if (input[position] == "-")
nextToken = MINUS_CODE;
else if (input[position] == "^")
nextToken = EXP_CODE;
else if (input[position] == "(")
nextToken = LEFT_PAREN_CODE;
else if (input[position] == ")")
nextToken = RIGHT_PAREN_CODE;
else
{
nextToken = ID_CODE;
nextValue = atoi(input[position].c_str());
}
printf( "Call lex /* returns %s */\n",input[position].c_str());
position++;
}


To run that code you need the following dependency:
http://www.codeproject.com/string/stringsplit.asp

@Nidhogg - C++ adds more, so you can use less :angel:
I could never be a C purist, because it would force me to write code like the above abomination. OOP + Me = <3

Nidhogg
05-03-09, 20:25
If you want the purity of C and the power of OO, you choose C#, not C++. :p

BTW, prefix notation used to be called Reverse Polish Notation back when I was a lad. ;) I guess they didn't like the Polish part of the name. Eeeh, I remember writing a user exit for Oracle's SQL*Forms v2 using Pro*COBOL to allow you to write RPN calculations directly into triggers. This was back when SELECTing from SYSTEM.DUAL just to do some maths was very expensive.

Yes, writing a calculation engine in COBOL. Now *that's* a challenge. :p

N

Rambus
05-03-09, 20:34
C# is very, very nice language from a programmers point of view.
-Garbage collection
-Bounds checking
-.Net framework
-... a gazillion other things

I'm a daily C++ coder so C# is kind of like having cake instead of bread for me.
That being said, C++ has
-Better performance
-portability
-Multiple inheritance
-Macros
-Default args can be defined on function params
-... more stuff

Performance + Portability is why C++ still has the game dev crown :)


Edit: Cobol.. Ack! keep that away from me lol. I remember writing a similar calc program in Lisp and I started thinking it might be a great language until I tried to solve a more linear problem :P

Nidhogg
05-03-09, 20:59
That being said, C++ has
-Better performance
-portability
-Multiple inheritance
-Macros
-Default args can be defined on function params
-... more stuff

Performance + Portability is why C++ still has the game dev crown :)

See, I would say some of those things are bad. Multiple inheritance is a terrible feature and leads to awful, awful code. Interfaces are much cleaner which is why nearly all languages since C++ use them.

C# progams are not only portable across systems running the .NET framework (i.e. Windows ;)), but they're also portable against any other language that compiles down to the CLR. Actually, Silverlight comes with a small version of the .NET framework and that runs on MacOS and Linux these days.

Default function arguments are another terrible coding practice that leads to confusing code. I would argue that it's far better to define overloaded methods to do the same thing (e.g. a method with one parameter that calls an overloaded version of itself, specifying the default parameter that way).

Macros are another thing that can lead to code that's extremely difficult to follow and debug. The problems that macros solved don't really exist in modern languages anyway so they shouldn't really be used in this day and age.

Ah, language wars. Gotta love 'em!

N

P.S. Has Nobby come back to check his thread yet??

Biglines
05-03-09, 21:55
lol @ a mod starting an unwinnable discussion on a forum :D

well... i suppose him being a mod actually makes it a winnable discussion ;)

Rambus
05-03-09, 22:48
@Nidhogg - I was almost going to put a * next to multiple inheritance point in my post but decided to let it slide!

(For added flame bait only) 'Bzzzt wrong!' All of those things are valuable if used properly, heck even a goto statement has a legitimate performance based use in code. Multiple inheritance is used in several critical and valuable design patterns.

Being able to use C#, J#, VB.net to compile to the same CLR byte code is not the same as having a portable language. .Net is proprietry, end of story. Mono and other compilers/frameworks exists to allow C# code to be sort of 'portable', but still doesn't come close to matching the speed of C++.


I would argue that it's far better to define overloaded methods to do the same thing (e.g. a method with one parameter that calls an overloaded version of itself, specifying the default parameter that way).
Sounds like a mess! Also it shows the different viewpoints we have towards programming, you would rather push two AR's to the stack for every invocation then have a minor readability issue. (solved by modern IDE's)


Macros are another thing that can lead to code that's extremely difficult to follow and debug. The problems that macros solved don't really exist in modern languages anyway so they shouldn't really be used in this day and age.

Macros are a very helpful tool for creating a cross platform/cross build solution.. I guess being a C# coder you wouldn't know too much about that (kidding! that was really a joke!!) They can easily be misused like many features of C++.

As Biglines stated this is a 'unwinnable war'. The languages have their own uses and charm. The right tool for the job should be used.

I wounder what language the Black Prophecy engine is written in :angel:

Nidhogg
05-03-09, 23:30
Your last line is the key. Different tools for different jobs.

If I was writing something that required maximum performance then I would also choose C++. ;)

N

Rambus
05-03-09, 23:34
Actually, my real last line was additional flame bait ;)

Biglines
06-03-09, 00:26
pff, c++ is for noobs, assembly is for real men!

lol sorry for the flame (no intention of closing the thread, so if this is not supposed to be here, plz don't close but remove my reply ;))

Rambus
06-03-09, 00:45
Mips or X86? (I find mips a dream to code with compared to x86..)

Ps. You only get the real, mean speed if you use punch cards!

nobby
06-03-09, 11:37
Hello guys back again, I must say... wow!

Never expected so much input from you all.

and Nidhogg... hehe

I'm going to switch from C++ to LOLCODE me thinks...


thankyou all :p

rob444
07-03-09, 01:17
rambus, leaving #neocron on ETG is like leaving your family, get back in there you noob!

nobby
09-03-09, 12:56
Would you guys be able to explain to me what the following things mean within C++.

naming conventions, local and global variables, arrays; loops e.g. conditional (pre-check, post-check), fixed; confitional statements; case statements; logical operators ; assignment statements; input statements; output statements.

Just came across all these now on my unit and wondered if anyone could help me understand these better :)

Biglines
09-03-09, 13:16
.... those are basic terms in programming, don't u get like a boom or something? if not... buy one

nobby
09-03-09, 13:44
I suppose you mean "book"

We never got one and the ones in the library are too outdated and boring as muff.


I have looked, but really need a layman's description to really understand : \

Biglines
09-03-09, 13:50
get a C++ for dummies book then, cuz those terms aren't explained easily... for example naming conventions are conventions for naming variables and stuff, but to actually know all those conventions u need a book or a website (there's loads of c++ tutorials around the web...)

zii
10-03-09, 21:47
#!/iloveyou/myfriend/perl
use whc;
$sum = "@ARGV";
$result = 0;

if (! $sum) {
while (1) {
print "Calculater- reporting for duty: ";
chop ($sum = <STDIN>);
last unless ($sum);
calc();
}
} else {

calc();

}
#
sub calc{

$sum =~ s/\$/($result)/;
$result = eval ($sum);
print "result: $result \n";
}

danmalone
10-03-09, 23:03
Im surprised Mighty Max hasnt come along and contributed...

He could kill you all with one line of code :p

StevenJ
10-03-09, 23:39
Im surprised Mighty Max hasnt come along and contributed...

He could kill you all with one line of code :p
MM uses his powers for good.

Nobby, if you need any quick help with programming, shout on msn :)

Rambus
24-03-09, 04:28
rambus, leaving #neocron on ETG is like leaving your family, get back in there you noob!

My university computer is banned from ETG for some reason :(

rob444
24-03-09, 09:49
My university computer is banned from ETG for some reason :(

Excuses excuses ;). Use tunneling then ^^