Arithmetic
-
Upload
michael-gordon -
Category
Business
-
view
1.110 -
download
0
description
Transcript of Arithmetic
![Page 1: Arithmetic](https://reader035.fdocuments.net/reader035/viewer/2022081807/54bee7674a795991698b45fc/html5/thumbnails/1.jpg)
CS111 Lab Arithmetic
Instructor: Michael Gordon
![Page 2: Arithmetic](https://reader035.fdocuments.net/reader035/viewer/2022081807/54bee7674a795991698b45fc/html5/thumbnails/2.jpg)
C++ Arithmetic Operators
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (remainder)
() Parentheses
![Page 3: Arithmetic](https://reader035.fdocuments.net/reader035/viewer/2022081807/54bee7674a795991698b45fc/html5/thumbnails/3.jpg)
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](https://reader035.fdocuments.net/reader035/viewer/2022081807/54bee7674a795991698b45fc/html5/thumbnails/4.jpg)
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](https://reader035.fdocuments.net/reader035/viewer/2022081807/54bee7674a795991698b45fc/html5/thumbnails/5.jpg)
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](https://reader035.fdocuments.net/reader035/viewer/2022081807/54bee7674a795991698b45fc/html5/thumbnails/6.jpg)
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](https://reader035.fdocuments.net/reader035/viewer/2022081807/54bee7674a795991698b45fc/html5/thumbnails/7.jpg)
Type casting
Reverse example (double to int)
Drops the decimal part
double total = 100.5;
int value = (int) total;
value now equals 100.