Hi,
Right oh, you asked for it, here goes ....... :+)
Avoid having line 7, just put
std::
before each std thing. Believe me, it's the best way, all the experts do that. Google it.
Don't use
std::endl
, it flushes the buffer and could be inefficient for a larger program. Put
'\n'
in your output:
std::cout << "Welcome to the calculator program!\n";
Use functions. A function should do 1 conceptual thing, and shouldn't be any longer than 40LOC, this includes
main
within reason. So the menu, each +-/* operation should all have their own functions. Getting the input for x and y should be a function too, then you don't have to repeat that code throughout the program. Using functions aids understanding, it's a simple form of abstraction. Choose meaningful names for them, and provide a comment on what the function does.
Delay the declaration of a variable until you have a sensible value to initialise with. Do the declaration and initialisation on one line. Write a comment about it's expected valid ranges. Choose a meaningful name for variables, it's a misnomer to over abbreviate everything. For example,
quotient
instead of
quo
Prefer
double
instead of
float
, unless using some graphics library which requires it. Float is easily exceeded, that is why double is the default for literals.
Prefer a single
char
or
int
as a choice value. Using
std::string
makes your code fail if 1 char is the wrong case, or the word is misspelt, or otherwise not the same as your code. Use the
std::toupper
or
std::tolower
on the
char
, then you you don't have to worry about the upper / lower case of it. Then you can use a
switch
with a
default
case to catch bad input.
enum
can also be used for the individual
case
s. Compiler warnings can be turned on if not all the
enum
's have a matching
case
. Each
case:
of the
switch
should call a function.
I am not a fan of
do
loops. All 3 looping constructs can be converted from one to another, maybe at the price of an extra variable. So I prefer to use a
while
loop in this situation. Just because one wants the code to execute at least once should not be a sole consideration for using a
do
loop IMO. You can make use of a
bool Quit
value to control the loop.
Why does everyone forget to check for division by zero? One must consider anything that may go wrong, and write code to defend against those things.
A sqrt function should check to see if the argument is positive, otherwise the program will crash with an un-handled exception
Your code also needs indentation, your editor in your IDE should do this for you, auto-magiacally.
Good Luck, hopefully you found all this helpful :+)
Edit: