Saturday, October 15, 2011

1.4. Basic mathematical operations in C#

The symbol for the sum is +, and - for the subtraction, but other mathematical operations have less intuitive symbols. Let's see the most important ones:

Operator Operation
+ Sum
- Subtraction, negation
* Multiplication
/ Division
% Remainder of the division ("modulus")

Suggested exercises:
  • Create a program to calculate the product of 12 and 13.
  • Write a program that calculates the difference (subtraction) between 321 and 213.
  • Make a program that computes the result of dividing 301 by 3.
  • Create a program that calculates the remainder of the division of 301 by 3.

1.4.1. Precedence of the operators

It's not difficult:
  • First, the operations indicated in parentheses.
  • Then the negation
  • After that, multiplication, division and the remainder of the division.
  • Finally, addition and subtraction.
  • If two operations have the same priority, they are analyzed left to right.

Suggested exercise: Calculate (by hand and then check it using C#) the result of the following operations:
  • -2 + 3 * 5
  • (20+5) % 6
  • 15 + -5*6 / 10
  • 2 + 10 / 5 * 2 - 7 % 1

1.4.2. Introduction to overflow problems

The space available for storing numbers is limited. If the result of an operation is "too big", we will get an error message or a wrong result. Because of this, in out first examples we will use small numbers. Later we will see the reason this problem and how to avoid it. As a example, the following program does not even compile because the compiler knows that the result will be "too big":



public class MultiplyOverflow
{
public static void Main()
{
System.Console.WriteLine(10000000*10000000);
}
}
 

No comments:

Post a Comment