Arithmetic

7
CS111 Lab Arithmetic Instructor: Michael Gordon

description

 

Transcript of Arithmetic

Page 1: Arithmetic

CS111 Lab Arithmetic

Instructor: Michael Gordon

Page 2: Arithmetic

C++ Arithmetic Operators

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus (remainder)

() Parentheses

Page 3: Arithmetic

Order of Operations

()

* / %

+ -

(4 + 2) / 2 + 4 = ???

Operation in () first: 4+2=6

Division next: 6 / 2 = 3

Last addition, 3 + 4 = 7

Page 4: Arithmetic

Integer and Decimal Division

Division of two integers drops the decimal:

5 / 2 = 2 (not 2.5)

4 / 2 = 2

Division involving a double type, will result in a double result (with decimal)

5 / 2.0 = 2.5

4 / 2.0 = 2

One or both numbers must be a double

Same rules apply to addition, subtraction and multiplication.

Page 5: Arithmetic

Data Types and Order

Sample operations and resulting data

types:

6.0 + 5 / 2

Result of first operation: int

Result of second operation: double

• 5 + 5 / 2.0

Result of first operation: double

Result of second operation: double

Page 6: Arithmetic

Type casting

Type casting changes one type to

another.

For example if you want a double type

result of integer division, you can do this:

double result = (double) 5 / 2

result now equals 2.5

Page 7: Arithmetic

Type casting

Reverse example (double to int)

Drops the decimal part

double total = 100.5;

int value = (int) total;

value now equals 100.