Transcript data_input

Data Types and Input
01/31/11
Today
• Quiz 1
• Use correct data types
• Write input statements using cin
Data Types
•
•
•
•
•
double
int
char
bool
string
Floating Point
In Memory:
mantissa
exponent
Number = mantissa x 2exponent
Floating Point
• Type double
–
–
–
10-307 to 10308
15 significant digits
Numbers with decimal points
• Example Constants
– . 45.7, 8.97e-4, -15.4
– e-format ^
8.97 x 10 -4
• Not exact
• Also float & double long
int
• Binary number with sign
• In memory:
Sign bit
• e.g. 100, 15, 0, -19, -100000
• -2,147,483,647 to 2,147,483,647
• Also short and long
Numeric Errors
• Overflow
– Attempt to represent value too large for the
type
• Underflow
– Attempt to represent value too small for the
type
• Cancellation Error
– Attempt to add tiny fraction to large number
– 4000000000 + .00000002
char
• Stores a single character
• Enclosed in single quotes
• e.g. 'a' '4' '$'
• Some characters with \
• \ part of escape sequence
– '\n'
'\t'
'\''
'\\'
char
• Values
‘0’<‘1’<‘2’< … < ‘9’
‘A’<‘B’<‘C’< … <‘Z’
‘a’<‘b’<‘c’< … <‘z’
Other types
• bool
– true, false
• string
– double quotes
– Example:
cout << “Hi!”;
• #include <string>
– Allows variables
Variable
• Place in memory to store data
– Can only hold one value at a time.
• Must be declared in C++
• Declaration gives the variable a type
• Example Declarations:
int count;
double gallons;
char initial;
Input
Input
cin >> mass;
• cin
– Input stream
– Standard input, usually keyboard
• >>
– Extraction operator
Input
cin >> rate;
• Waits for input from user
• Stores value in the variable
• Must hit [Enter]
• Skips spaces and newline characters
Input
cout << “Enter rate:”;
cin >> rate;
Execution :
Enter rate:
67
Input
cout << “Rate and time?”;
cin >> rate >> time;
Execution :
Rate and time?
5
2
Input Characters
char let1, let2;
cin >> let1 >> let2;
• Inputs single characters
• Skips whitespace
• Example: inputChar.cpp
Example
The formula to find the area of an ellipse
is:
Area = πab
Using this formula, write a C++ program to
calculate the area of an ellipse after
asking the user for the minor axis, a, and
the major axis, b.
Algorithm
1. Input a
2. Input b
3. Area = πab
4. Output Area
Program
• Let's write and submit the program on onyx.
– handout
Next
• Discuss Arithmetic Expressions
• Sections 2.5 and 2.6
Constants for Permanent
Values
Constants
• Sometimes a number like 9.8 m/sec2 is
used in several spots in a program.
– Easy to make mistake in repeated
keying.
– The purpose of the number may not be
obvious
• “Magic Number”
– Change must be made in several
spots.
Constants
• Nice to give constants names:
const double g = 9.8;
• Add it to leadwgt.cpp