Subtraction is fairly straightforward in C#. To subtract one number
from another, you use the minus symbol ( - ).
Add another button to your form. Set the following properties for it in the
Properties Window:
Name: btnSubtract
Size: 100, 30>
Text: Subtract
Double click the button to get at the code. Add the following three lines of
code:Size: 100, 30>
Text: Subtract
int answerSubtract;
answerSubtract = 50 - 25;
MessageBox.Show( answerSubtract.ToString() );
Your coding window will then look like this:Run your code, and make sure it works. The answer you should see in the message box is, of course, 25. Stop your programme and return to the coding window. Now change the 25 to 25.5.
answerSubtract = 50 - 25.5;
Try to run your programme and you'll get the blue wiggly line, meaning there's
an error in your code. The reason is the same as for addition: we're trying
to place a float number into an integer variable (the answer will be 24.5, this
time). Just because the math symbol has changed doesn't mean we can disobey
the C# rules!Change it back to 25, and the code will run fine.
As with addition, you can subtract more than one number. Change your line to this:
answerSubtract = 50 - 25 - 10 - 2;
When you run your programme, you should see 13 in your message box, the answer
to the subtraction.You can also use variable names in your subtraction. Add the following integer variable to your code:
int numberOne = 12;
Then change the second line to this:
answerSubtract = 50 - numberOne;
Here's what your coding window should look like:Run you programme and click your button. You should see an answer of 38 in your message box.
Set up another variable. Call it numberTwo. Place a value of 4 inside of this new variable. Subtract from 50 the value in numberOne and the value in numberTwo. When you run your code, the answer you get in the message box should be 34.
0 comments:
Post a Comment