You deserve some credit for getting this to work - though see comments below:
Your divide by zero check is done too late, after the divide has already been attempted. By then the program will
already have crashed (depending on system and/or compiler).
Also, I see you're still using goto :( rather than a structured loop.
http://www.cplusplus.com/doc/tutorial/control/
If you've learned about functions, I'd suggest making the code which gets an integer into a separate function, then you could just do something like:
or perhaps,
|
no1 = getDouble("Enter first number");
|
it helps to keep the clutter out of the main program, as well as re-using code rather than typing the same code twice.
http://www.cplusplus.com/doc/tutorial/functions/
You might do the same with the code which gets an operator. Even though called only once, again it can reduce clutter. The aim is to have the main control flow readable in terms of showing clearly what is going on, without getting bogged down in the messy details.
An example of how the main() function might look with a lot of the detail handed over to other functions. This allows the entire thing to be viewed without scrolling, and also makes the looping structure clear. Notice how clear things can be without those
goto
statements which rather than making things simple, serve to obscure the structure.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
int main()
{
cout << "This is a basic calculator. \n\n";
char yn = 'y';
while (yn != 'n')
{
double no1 = getDouble("Please enter first number: ");
char myoperator = getOperator();
cout << "The operator you have chosen is " << myoperator << endl;
double no2 = getDouble("Please enter second number: ");
while (myoperator == '/' && no2 == 0)
{
cout << "Cannot divide by Zero. ";
no2 = getDouble("Please enter second number: ");
}
double result = calculate(no1, no2, myoperator);
cout << no1 << ' ' << myoperator << ' ' << no2 << " = " << result << "\n\n";
cout << "Would you like to continue?\n";
do {
cout << "Press 'y' to continue or 'n' to exit: ";
yn = tolower(cin.get());
} while (yn != 'y' && yn != 'n');
}
}
|