C# Tutorial - Application 7 – Simplifying the CalculatorCreate a new console Application called App07. We are going to simplify the calculator, so that instead of having lots of ‘if’ statements, the operation is easier to read. The source code for the Main method of the application is given below. // Storage
int value1 = 0;
int value2 = 0;
double total = 0;
string operation;
// Get first number
value1 = GetNumber();
// Get Operation
Console.Write( "What operation would you like to perform: " );
operation = Console.ReadLine();
// Get second number
value2 = GetNumber();
// Perform the operation
switch( operation )
{
case "+": total = value1 + value2; break;
case "-": total = value1 - value2; break;
case "/": total = (double)value1 / (double)value2; break;
case "*": total = value1 * value2; break;
default: /* Ignore other keypresses */ break;
}
// Output the answer
Console.WriteLine( "The total is {0}", total );
This code is shorter than the previous application while providing slightly better functionality. In order to give better precision for division, total is now declared as a double. This is a decimal number, and hence will display the correct number when division is performed. The ‘switch’ statement allows a choice to be made dependant upon the value of the item in the brackets to the right of switch. The item may be either an integral or string value. In this case we are using a string to hold the contents of the key that has been pressed, and then a decision is made on the four keys that we are interested in.
|