Very simple calculator

Started by
21 comments, last by foxefde 10 years, 10 months ago

void means "doesn't return a value", so you cant do

somevariable = OutputEquation(3, '+', 4, 146000);

If you don't define all the arguments, it will fail to compile. (You'll find out about default arguments later, which means if you don't provide arguments they will be given the defaults you specify - don't worry about that yet).

A variable has to be initialised before it is read. You don't need to initialise a variable before you write to it though. Uninitialised variables get garbage values if they are on the stack (local variables), or are initialised to all zero bits if they are global. Free-store and heap variables (from malloc/new) can get initialised with garbage values too. Your compiler will (probably) warn you if you try and use an uninitialised local or heap/free-store variable.

"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley
Advertisement

I'm not convinced kPlus is better than '+' - both are constants anyway. That's a bit like defining ZERO as 0.

You gave a very good explanation for why defining the constants is a good idea (7 dwarves and 7 sins... nice), this is no different. The fact that he uses '+', '-', etc in multiple places means that defining it once is smart.

For example, lets say that instead of printing "2 * 10 = 20" he now wants to print "2 x 10 = 20"... change the constant in one place and it's done! The user can now enter 'x' instead of '*' and the code will recognize it, do the right thing, and print out the correct final output. Well, except for the instructions printed out to the user prompting for the input, which is still hard-coded... that I didnt change cause I was lazy... but this only shows that changing those also to use the kAdd, kMul, etc, would be a good idea.

Okay, so, should I be asking why it says void in front? Or will that just confuse me?

Sorry, I would have given a more detailed explanation, but I didnt realize you're still learning the basics of how functions work. But yeah, functions have input and output parameters. I dont want to try to explain more because you can probably learn this more effectively from whatever source you're currently using... and I dont want to further confuse you.

You want to create a simple calculator?What about this?

#include <iostream>
using namespace std;
int main()
{
double a,b;
char symbol;
cout << "CALCULATOR IS READY!\n";
do
{
cin >> a >> symbol >> b;
switch(symbol)
{
case '*':
cout << " = " << a * b << endl;
break;
case '+':
cout << " = " << a + b << endl;
break;
case '-':
cout << " = " << a - b << endl;
break;
case '/':
cout << " = " << a / b << endl;
break;
}
}
while(true);
}

This topic is closed to new replies.

Advertisement