Download Data Type and Expressions

Document related concepts

Elementary mathematics wikipedia , lookup

Transcript
Chapter 3
Expressions and Interactivity
1
Topics
3.1 The cin Object
3.2 Mathematical Expressions
3.3 When You Mix Apples and Oranges: Type
Conversion
3.4 Overflow and Underflow
3.5 Type Casting
3.6 Named Constants
2
Topics (continued)
3.7 Multiple Assignment and Combined
Assignment
3.8 Formatting Output
3.9 Formatted Input
3.10 More About Member Functions
3.11 More Mathematical Library Functions
3.12 Introduction to File Input and Output
3
3.1 The cin Object
 Standard input object
 Like cout, requires iostream file
 Used to read input from keyboard
 Often used with cout to display a user
prompt first
 Information retrieved from cin with >>
 Input information stored in one or more
variables
4
The cin Object
 User input goes from keyboard to keyboard
buffer
 cin converts information to the type that
matches the variable:
int height;
cout << "How tall is the room? ";
cin >> height;
5
The cin Object
 Can be used to input > 1 value:
cin >> height >> width;
 Multiple values from keyboard must be
separated by spaces
 Order is important: first value entered goes to
first variable, etc.
6
Example 1
// This program asks the user to enter the length and width of
// a rectangle. It calculates the rectangle's area and displays
// the value on the screen.
#include <iostream>
This program calculates the area of a rectangle.
using namespace std;
Enter the length and width of the rectangle separated by a space.
int main()
{
int length, width, area;
10 20 [Enter]
The area of the rectangle is 200
cout << "This program calculates the area of a ";
cout << "rectangle.\n";
cout << "Enter the length and width of the rectangle ";
cout << "separated by a space.\n";
cin >> length >> width;
area = length * width;
cout << "The area of the rectangle is " << area << endl;
return 0;
}
7
Example 2
// This program demonstrates how cin can read multiple values
// of different data types.
#include <iostream>
using namespace std;
Enter an integer, a float, and a character: 4
5.7
4 b [Enter]
5.7
[Enter]
int main()
{
int whole;
float fractional;
char letter;
Whole:4
Whole:
Fractional: 5.7
Letter: b
cout << "Enter an integer, a float, and a character: ";
cin >> whole >> fractional >> letter;
cout << "Whole: " << whole << endl;
cout << "Fractional: " << fractional << endl;
cout << "Letter: " << letter << endl;
return 0;
}
5
.
7
4
b
[Enter]
8
The cin Object
 Can be used to read in a string
 Must first declare an array to hold characters in
string:
char myName[20];
 myName is name of array, 20 is the number of
characters that can be stored (the size of the
array), including the NULL character at the end
 Can be used with cin to assign a value:
cin >> myName;
9
Example
// This program demonstrates how cin can read a string into
// a character array.
#include <iostream>
using namespace std;
int main()
{
char name[21];
cout << "What is your name? ";
cin >> name;
cout << "Good morning " << name << endl;
return 0;
}
10
3.2 Mathematical Expressions
 Can create complex expressions using
multiple mathematical operators
 An expression is a programming statement
that has a value. It can be a constant, a
variable, or a mathematical combination of
constants and variables
 Can be used in assignment, cout, other
statements:
result=x;
result=4;
area = 2 * PI * radius;
cout << "border is: " << 2*(l+w);
11
Order of Operations
Operator Precedence:
In an expression with > 1 operator, evaluate in this
order:
Do first
Do next
Do last
- (unary negation),
* / %,
+ -,
In the expression 2 + 2 * 2 – 2 ,
evaluate
second
evaluate
first
evaluate
third
12
Associativity of Operators
 - (unary negation) associates right to left
 *, /, %, +, - associate left to right
 parentheses ( ) can be used to override the
order of operations:
2
(2
2
(2
+
+
+
+
2
2)
2
2)
* 2 –
* 2 –
* (2 –
* (2 –
2
2
2)
2)
=
=
=
=
4
6
2
0
13
Converting Algebraic Expressions to
Programming Statements
 Multiplication requires an operator:
Area=lw is written as Area = l * w;
 There is no exponentiation operator:
Area=s2 is written as Area = pow(s, 2);
 Parentheses may be needed to maintain order of
operations:
y 2  y1
m
x 2  x1
is written as
m = (y2-y1) /(x2-x1);
14
Library function: pow
 pow(x, y): raise x to power y
x
y
pow function
x
y
 cmath header file: #include<cmath>
 return a double value
15
Example
// This program calculates the area of a circle.
// The formula for the area of a circle is Pi times
// the radius squared. Pi is 3.14159.
#include <iostream>
#include <cmath> // needed for pow function
using namespace std;
int main()
{
double area, radius;
cout << "This program calculates the area of a circle.\n";
cout << "What is the radius of the circle? ";
cin >> radius;
area = 3.14159 * pow(radius, 2);
cout << "The area is " << area << endl;
return 0;
}
16
3.3 When You Mix Apples and
Oranges: Type Conversion
 Operations are performed between operands
of the same type.
 If not of the same type, C++ will convert one
to be the type of the other
 This can impact the results of calculations.
17
Hierarchy of Types
Highest:
Lowest:
long double
double
float
unsigned long
long
unsigned int
int
Ranked by largest number they can hold
Exception: unsigned int outranks long
if int and long are the same size
18
Type Coercion
 Type Coercion: automatic conversion of an
operand to another data type
 Promotion: convert to a higher type
 Demotion: convert to a lower type
19
Coercion Rules
1) char, short, unsigned short
automatically promoted to int
Exception: unsigned short is promoted
to unsigned int if short and int are in
the same size
2) When operating on values of different data
types, the lower one is promoted to the type
of the higher one.
3) When using the = operator, the type of
expression on right will be converted to type
of variable on left
20
Example
int x, y=4;
float z=2.7;
x=y*z;
cout<<x;
y*z=10.8
x=10
21
3.4 Overflow and Underflow
 Occurs when assigning a value that is too
large (overflow) or too small (underflow) to be
held in a variable
 Variable contains value that is ‘wrapped
around’ set of possible values
22
Example
// This program demonstrates integer overflow and underflow.
#include <iostream>
using namespace std;
int main()
{
short testVar = 32767;
cout << testVar << endl;
testVar = testVar + 1;
cout << testVar << endl;
testVar = testVar - 1;
cout << testVar << endl;
return 0;
32767
-32768
32767
}
short ranges -32,768 to +32,767
23
Handling Overflow and Underflow
 Different systems handle the problem differently.
They may

display a warning / error message

stop the program

or just continue execution
24
3.5 Explicit Type Conversion
 Also called type casting
 Used for manual data type conversion
 Format
static_cast<type>(expression)
 Example:
cout << static_cast<char>(65);
// Displays ‘A’
25
More Type Casting Examples
 Useful to see int value of a char variable:
char ch = 'C';
cout << ch << " is stored as "
<< static_cast<int>(ch);
 Useful for floating point division using ints:
float m = static_cast<float>(y2-y1)/(x2-x1);
26
C-Style and Prestandard Type Cast
Expressions
 C-Style cast: data type name in ()
cout << ch << " is " << (int)ch;
 Prestandard C++ cast: value in ()
cout << ch << " is " << int(ch);
 Both are still supported in C++, although
static_cast is preferred
27
Ex. What are the values of the
following expressions:
int a=5, b=12;
double x=3.4, z=9.1;
A) b/a
B) x*a
C) static_cast<double>(b/a)
D) static_cast<double>(b)/a
E) b/static_cast<double>(a)
F) static_cast<double>(b)/static_cast<double>(a)
G) b/static_cast<int>(x)
H) static_cast<int>(x) * static_cast<int>(z)
I) static_cast<int>(x*z)
J) static_cast<double>(static_cast<int>(x)*static_cast<int>(z))
•28
Ex. What will the following program display?
#include <iostream>
using namespace std;
int main()
{
int integer1, integer2;
float float1;
integer1 = 19;
integer2 = 2;
float1 =integer 1/ integer2;
cout << float1 <<endl;
float1 = static_cast<float>(integer1) / integer2;
cout << float1 <<endl;
float1 = static_cast<float>(integer1 / integer2);
cout <<float1 <<endl;
return 0;
}
29
3.6 Named Constants
 Named constant (constant variable): variable
whose content cannot be changed during
program execution
 Used for representing constant values with
descriptive names:
const float TAXRATE = 0.0675;
const int NUMSTATES = 50;
 Often named in uppercase letters
30
const vs. #define
 #define
 C-style of naming constants
#define NUMSTATES 50



no ;
goes here
Interpreted by pre-processor rather than compiler
Does not occupy a memory location like a
constant variable defined with const
Instead, causes a textual substitution to occur. In
above example, every occurrence in program of
NUMSTATES will be replaced by 50
31
Example 1
// This program calculates the area of a circle.
// The formula for the area of a circle is pi times
// the radius squared. Pi is 3.14159.
#include <iostream>
#include <cmath> // needed for pow function
using namespace std;
int main()
{
const float PI = 3.14159;
double area, radius;
cout << "This program calculates the area of a circle.\n";
cout << "What is the radius of the circle? ";
cin >> radius;
area = PI * pow(radius, 2);
cout << "The area is " << area << endl;
return 0;
}
32
Example 2
// This program calculates the area of a circle.
// The formula for the area of a circle is Pi times
// the radius squared. pi is 3.1459.
#include <iostream>
#include <cmath> // needed for pow function
using namespace std;
#define PI 3.14159
int main()
{
double area, radius;
cout << "This program calculates the area of a circle.\n";
cout << "What is the radius of the circle? ";
cin >> radius;
area = PI * pow(radius, 2);
cout << "The area is " << area << endl;
return 0;
}
33
3.7 Multiple Assignment and
Combined Assignment
 The assignment operator (=) can be used > 1
time in an expression
x = y = z = 5;
 Associates right to left
x = (y = (z = 5));
Done
3rd
Done
2nd
Done
1st
34
Combined Assignment
 Applies an arithmetic operation to a variable and
assigns the result as the new value of that
variable
sum = sum + newnum;
Note: not an algebraic equation!
 Operators: +=
-=
*=
/=
%=
 Example:
sum += amt; is “short” for sum = sum + amt;
35
More Examples
x
x
x
x
x
+=
-=
*=
/=
%=
5;
5;
5;
5;
5;
means
means
means
means
means
x
x
x
x
x
=
=
=
=
=
x
x
x
x
x
+
–
*
/
%
5;
5;
5;
5;
5;
 The entire right hand side is evaluated before the
combined assignment operation is done.
x *= a + b; means
x = x * (a + b);
36
More Examples
 Prog 3-13
37
3.8 Formatting Output
 Can control how output displays for numeric,
string data:



size
position
number of digits
 Requires iomanip header file:
#include<iomanip>
38
Stream Manipulators
 Used to control features of an output field
 Some affect just the next value displayed:
setw(n): print in a field at least n spaces wide. Use more
spaces if field is not wide enough
 Some affect values until changed again:
 fixed: use decimal notation for floating-point values
 setprecision(n):
 When used with fixed, print floating-point value using n
digits after the decimal.
 Without fixed, print floating-point value using n
significant digits
 showpoint: always print decimal for floating-point values
 left: cause output is left-justified
39
 right: cause output is right-justified

Manipulator Examples
const float e = 2.718;
float price = 25.0;
cout << setw(8) << e << endl;
cout << setprecision(2);
cout << e << endl;
cout << fixed << e << endl;
cout << setw(6)
<<showpoint<< price;
Displays
^^^2.718
2.7
2.72
^25.00
40
Ex. Write cout statements with stream
manipulators that perform the following:
A) Display the number 34.789 in a field
of nine spaces with two decimal
places of precision
B) Display the number 7.0 in a field of
five spaces with three decimal places
of precision. The decimal point and
any trailing zeroes should be
displayed.
C) Display the number 67 left justified
in a field of seven spaces
41
3.9 Formatted Input
 Can format field width for use with cin
 setw(n)
 Useful when reading string data to be stored
in a character array:
char fName[10];
cout << "Enter your name: ";
cin >> setw(10) >> fName;
 cin reads one less character than specified
in setw() directive
42
Formatted Input
 To read an entire line of input, use
cin.getline(
)
char address[81];
cout << "Enter your address: ";
cin.getline(address, 81);
 cin.getline takes two arguments:
 Name of array to store string
 Size of the array
43
Formatted Input
 To read a single character:
 Use cin:
char ch;
cout << "Strike any key to continue";
cin >> ch;
Problem: will skip over blanks, tabs, <CR>

Use cin.get():
cin.get(ch);
Will read the next character entered, even whitespace
44
Formatted Input
 Mixing cin and cin.get() in the same program can
cause input errors that are hard to detect
char ch; //Define a character variable.
int number; //Define an integer variable.
cout << “Enter a number:”;
cin >> number; //Read an integer
cout << “Enter a character: “;
cin.get(ch); //Read a character.
cout << “Thank You!\n”;
1
0
0
[Enter]
45
Formatted Input
 To skip over unneeded characters that are still in the keyboard
buffer, use cin.ignore():
cin.ignore(); // skip next char
cin.ignore(10, '\n');
// skip the next 10 char. or until a '\n'
char ch; //Define a character variable.
int number; //Define an integer variable.
cout << “Enter a number:”;
cin >> number; //Read an integer
cin.ignore( ); // Skip the new line character
cout << “Enter a character: “;
cin.get(ch); //Read a character.
cout << “Thank You!\n”;
46
3.10 More About Member
Functions
 Member Function: procedure that is part of an
object
 cout, cin are objects
 Some member functions of the cin object:



getline: cin.getline(address, 81);
get: cin.get(ch);
ignore: cin.ignore(); cin.ignore(10,
'\n');
47
3.11 More Mathematical Library
Functions
 Require cmath header file
 Take double as input, return a double
 Commonly used functions:
sin
cos
tan
sqrt
log
abs
Sine
Cosine
Tangent
Square root
Natural (e) log
Absolute value (takes and returns an int)
48
More Mathematical Library
Functions
 These require cstdlib header file
 rand(): returns a random number (int)
between 0 and the largest int the compute
holds. Yields same sequence of numbers each
time program is run.
 srand(x): initializes random number
generator with unsigned int x
49
Example
// This program demonstrates random numbers.
#include <iostream>
#include <cstdlib>
Enter a seed value: 5 [Enter]
using namespace std;
1731
int main()
{
unsigned seed;
cout << "Enter a seed value: ";
cin >> seed;
srand(seed);
cout << rand() << endl;
cout << rand() << endl;
cout << rand() << endl;
return 0;
}
32036
21622
Enter a seed value: 16 [Enter]
5540
29663
9920
50
Random number generator
 srand(time(NULL)):


makes use of the computer's internal clock to
control the choice of the seed. Since time is
continually changing, the seed is forever
changing. Remember, if the seed number
remains the same, the sequence of numbers
will be repeated for each run of the program.
#include <time.h>
51
Generating random numbers
within a specified range:
 x = minValue + rand( ) % n;


minValue = the smallest number in your range
n = the number of values in the range

n is computed by the largest (maxValue) – the
smallest (minValue) + 1
52
3.12 Introduction to File Input and
Output
 Can use files instead of keyboard, monitor
screen for program input, output
 Allows data to be retained between program
runs since files are stored on secondary
storage media, such as disk
 Steps:



Open the file
Use the file (read from, write to, or both)
Close the file
53
Files: What is Needed
 Use fstream header file for file access
 File stream types:
ifstream for input from a file
ofstream for output to a file
fstream for input from or output to a file
 Define file stream objects:
ifstream infile;
ofstream outfile;
54
Opening Files
 Create a link between file name (outside the
program) and file stream object (inside the program)
 Use the open member function:
infile.open("inventory.dat");
outfile.open("report.txt");
 Filename may include drive, path info.
outputFile.open(“a:\\invtry.dat”);
 Output file will be created if necessary; existing file
will be erased first
 Input file must exist for open to work
55
Using Files
 Can use output file object and << to send data
to a file:
outfile << "Inventory report";
 Can use input file object and >> to copy data
from file to variables:
infile >> partNum;
infile >> qtyInStock >>
qtyOnOrder;
56
Closing Files
 Use the close member function:
infile.close();
outfile.close();
 Don’t wait for operating system to close files
at program end:


may be limit on number of open files
may be buffered output data waiting to send to
file
57
Example 1
// This program uses the << operator to write information to a file.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream outputFile;
outputFile.open("demofile.txt");
On Screen
Now writing data to the file.
Done.
cout << "Now writing information to the file.\n";
// Write 4 great names to the file
outputFile << "Bach\n";
outputFile << "Beethoven\n";
outputFile << "Mozart\n";
outputFile << "Schubert\n";
// Close the file
outputFile.close();
cout << "Done.\n";
return 0;
In demofile.txt
Bach
Beethoven
Mozart
Schubert
}
58
Example 2
// This program uses the >> operator to read information
// from a file.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream inFile;
char name[81];
inFile.open("demofile.txt");
cout << "Reading information from the file.\n\n";
inFile >> name;
cout << name << endl;
// Display name 1
inFile >> name;
cout << name << endl;
// Display name 2
inFile >> name;
cout << name << endl;
// Display name 3
inFile >> name;
cout << name << endl;
// Display name 4
inFile.close();
cout << "\nDone.\n";
return 0;
On Screen
Reading data from the file.
Bach
Beethoven
// Read name 1 from the file Mozart
Schubert
// Read name 2 from the file
// Read name 3 from the file
Done.
// Read name 4 from the file
// Close the file
}
59
Class review
 The cin Object





requires iostream file
read input from keyboard
Information retrieved from cin with >>
Can be used to input > 1 value
Order is important
 Mathematical Expressions



Order of the operations:
Parentheses overrides the order of operations
pow(x,y), include<cmath>, double
 Type conversion

Operations are performed between operands of the same type.

If not of the same type, C++ will convert one to be the type of the other

Type coercion, promotion, demotion

Lower->higher; “=“: left->right
60
Class review
 Overflow and Underflow

Occurs when assigning a value that is too large (overflow) or too small
(underflow) to be held in a variable
 type casting

Used for manual data type conversion

static_cast<type>(expression)
char ch = 'C';
cout << ch << " is stored as " << static_cast<int>(ch);
 Multiple Assignment and Combined Assignment
 Formatting Output
#include<iomanip>
setw(n), fixed, setprecision(n), showpoint, left, right
 Formatted Input


To read an entire line of input, use cin.getline(a, b)
To read a single character: cin, cin.get(a)
 Member function
61