Lec3.ppt

advertisement
More C++ Basics
Chapter 3 Lecture
CSIS 10A
1
Agenda
Review 
C++ Standard Numeric Types
Arithmetic–way more than you want!
Character (char) data type
For Loop
Syntax, Run-time and Logical Errors
2
Review:
Standard Program Structure
To solve most problems, your main() program
will generally look like this (conceptually)
1. Declare variables for input, result and
intermediate data
2. Ask for data (cout)
3. Input data (cin)
4. Calculate result
5. Output result (cout)
3
An interactive C++ program:
//circle.cpp Calculate area of a circle
//
given a radius value
#include <iostream>
using namespace std;
int main()
{ int area, radius;
cout << "enter a radius: ";
cin >> radius;
area = radius * radius * 3.14;
cout << "the area is " << area << endl;
return 0;
}
4
A small problem…
Run circle.cpp:
enter a radius: 1
the area is 3
Press any key to continue . . .
But according to our code, it should be 3.14
What happened?
5
We used the wrong data type!
Go back, change:
int area, radius;
To:
float area, radius;
Now it works…the lesson?
1) Data types are important!
2) Testing is important!
6
Agenda
Review
C++ Standard Numeric Types 
Arithmetic–way more than you want!
Character (char) data type
For Loop
Syntax, Run-time and Logical Errors
7
Basic C++ Data Types
int – Represents integers
float – Represents real (floating point)
numbers
char – Represents characters (single
letters)
8
Integers only store whole numbers
int a=4;
int a=4.579132;
// puts 4 in a
// puts 4 in a
INTS are great for loop counters, representing
inventory, numbers of “things”
9
Trivia—other integer types
uses
range of values
short..............(2 bytes)….-32,767 to 32767
long …….….(4 bytes)…-2 bill to +2 billion
int ………….(depends)…long (sometimes short)
unsigned short (2 bytes)…0 to 65535
unsigned long ...(4 bytes) …0 to 4 billion
10
Beware Integer wraparound
// wrap.cpp
b is -294967296
int a, b, c;
c is 1705032704
a = 2000000000;
b = 2 * a;
c = 3 * a;
cout << "b is " << b << endl;
cout << "c is " << c << endl;
11
FLOATING-POINT Types
float is used to represent numbers with a
fractional part such as 2.543 or 6.45 etc…
or really big numbers that won’t fit inside ints
uses
range
precision
float...........(4 bytes)……10-38 to 1038……..6 digits
double…...(8 bytes)……10-308 to 10308…...15 digits
long double (10 bytes)....10-4932 to 104932…19 digits
12
What does floating point mean?
Consider a number like 123.45
“Float” the point so that all the digits are on its
right
(here the point is shifted 3 digits to the left)
123.45 = 0.12345 x 10 3
E-notation: the letter ‘e’= “x10 to the power of”
You can actually enter or display data using ‘e’:
123.45 same as 0.12345e3 same as 1.2345e2 13
Fine….
How is this stored in a float variable ??
The mantissa .12345 and the exponent 3 are
stored separately (in a variable)
For a 32 bit float type :
23 bit mantissa + 8 bit exponent + 1 sign bit
For a 64 bit double type :
52 bit mantissa + 11 bit exponent + 1 sign bit
14
Implications for Accuracy
(round-off error)
A float only stores about 6 digits of mantissa
float PI=3.1415926535897932384626;
PI really contains 3.14159
float x=50000000000000.0, y=10000.0;
x=x+y; DOES NOT CHANGE X!!! (no room)
Use a double if you need more precision
double PI=3.141592653589793;
About 16 digits of mantissa
double x=50000000000000.0, y=10000.0;
x=x+y; DOES CHANGE X!!! (now there’s room)
15
Q1) Practice your Scientific Notation
(answers at end of slides)
1234.56 = ____________ x 10 ____
.03413= ____________ e ____
6.78 x 107 = ____________
5.32e-5 = ____________
16
Displaying Floating Point data
cout
cout
cout
cout
cout
cout
cout
<<
<<
<<
<<
<<
<<
<<
Output
4.5
4.5 << endl;
-0.375
-.375 << endl;
10.6667
10.6666666 << endl;
6.78e+07
67800000.0 << endl;
523000000000 << endl; 3308957184
523000000000. << endl; 5.23e+11
9.8e-05
0.000098 << endl;
This is an integer, no ‘.’
17
For this to work,
#include<iomanip>
Formating Floating Point Output
cout<<fixed<<showpoint<<setprecision(2);
cout
cout
cout
cout
cout
cout
cout
<<
<<
<<
<<
<<
<<
<<
4.5 << endl;
-.375 << endl;
10.6666666 << endl;
67800000.0 << endl;
523000000000 << endl;
523000000000. << endl;
0.000098 << endl;
Output
4.50
-0.38
10.67
67800000.00
3308957184
523000000000.00
0.00
You can use this on problem 8
18
Constants are “variables”
-- that never change
Use the keyword “const” in front of declaration
You MUST provide initial value at declaration
const double PI=3.141592653589793;
const double METERS_PER_YARD = 0.9144;
const int MAX=1000;
Now you can say:
Don’t over do it:
area = PI * radius * radius;
const int SECONDS_PER_MINUTE = 60;
You can use a constant for problem 7
19
Agenda
Review
C++ Standard Numeric Types
Arithmetic–way more than you want! 
Character (char) data type
For Loop
Syntax, Run-time and Logical Errors
20
Arithmetic in C++
Basic operations + - * /
Math formulas need to be converted into
C++ syntax:
FORMULA
Equivalent C++
A = pr2
F = (v -a)
(v+a)
area=3.14*radius*radius;
force=(v-a)/(v+a);
21
More C++ Math Formulas
22
Arithmetic -- Order of Precedence
* and / are done first, then + and –
Equal levels are done left to right
Example:
3*4+2
2+3*4
6+4/2+3
6+ 2 +3
8 + 3
= 14
= 14
=
=
= 11
Parentheses have highest precedence (use if you want
different order)
(6 + 4) / (2 + 3) = 2
23
Q2) Practice Arithmetic Precedence
Evaluate the following
1+2 * 3 + 4
= _______
5+6/2*3
= _______
1 + 2 * (3 + 4) = _______
(7 + 5) / (2 * 3) = _______
24
Mixed-type Expressions
Expressions involving int and float will give a
result of type float (the most inclusive type)
Suppose you have
int n;
float
x;
Then
n + x
 results in float
n * 4
 results in int
n + 4.0
 results in double (4.0 is double)
(default for floating pt literals)
25
Mixed-type Assignments
Assigning int to float is perfectly safe
Assigning float to int may lose fractional part
Suppose you have
int n;
float
Then
1. x = 15;
2. n = 4.5;
x;
 stores 15 in x
 stores 4 in n -- Compiler Warning!
To satisfy the compiler for (2.) simply explain
your intentions:
n = int(4.5);
26
Q3) Can you guess what is stored in
these variables?
int m, n; double x,y;
m = 3.0;
n = 12.7;
x = m;
x = x + 0.5
m = m + 1;
y = x + 1;
m
n
x
y
?
?
?
?
27
Integer Division
CAUTION—this is a common C++ error
When both sides are int, the result MUST be int
9/2=4
9 / 10 = 0
Sometimes this is what we want
(convert inches to inches and feet)
Usually causes programming errors
When one side is float, the answer is float
9 / 2.0 = 4.5
9.0 / 10 = 0.9
28
Q4) Can you guess what is stored in
these variables?
int m, n; double x,y;
m = 10 / 3;
n = 30 / 7;
x = n * m;
y = 3 / 4 * x;
y = x * 3 / 4;
y = (x + 3) / 4;
m
n
x
y
?
?
?
?
29
One more thing…type-casting
If you want to perform floating point
division on a pair of integer variables, you
can…but you have to temporarily convert
one of them to float first:
int m=3, n=4;
float y;
y = float(m) / n;
( y = 0.75)
WRONG
y = float(m/n);
( y = 0)
30
Break Time!
Download Lab2MoreBasics.cpp
Work on problems 1-4, 7,8
Call me over if you have questions
31
Remainder % operator
The expression 10 / 3 gives the quotient, 3
We use 10 % 3 to get the remainder, 1
4/3 =1
12 % 6 = 0
4%3=1
13 % 6 = ____
2/3=0
14 % 6 = ____
2%3=2
23 % 7 = _____
Only use % on integers
32
What good is % operator?
You can use it to subdivide something into hierarchical
units:
int feet, inches;
cout << "Enter inches: ";
cin >> inches;
feet = inches / 12;
inches = inches % 12;
cout << feet << " ft. " << inches << " in.";
Enter inches: 75
6 ft. 3 in.
This is used in things like time, weight, length, change, etc.
Use this slide on Problem 9
33
Arithmetic Assignment Operators
Numeric operators +, -, *, /, % can be combined
with the assignment operator =
Saves time and typing
Only when you want to store result in one of operands
a
a
a
a
a
+=
-=
*=
/=
%=
b
b
b
b
b





a
a
a
a
a
=
=
=
=
=
a
a
a
a
a
+
*
/
%
b
b
b
b
b
34
Q5) Arithmetic Assign Operator Table
START: int x=0;
Shorthand
Same as
Result
x+=5;
x*=2;
x/=5;
x-=2;
x+=10;
x*=3;
x%=8
x/=5;
x=x+5;
x=x*2;
x=x/5;
x=x-2;
5
10
2
0
35
Agenda
Review
C++ Standard Numeric Types
Arithmetic–way more than you want!
Character (char) data type 
For Loop
Syntax, Run-time and Logical Errors
36
CHARACTER types (see Lab3-1)
char……………... (1 byte)
unsigned char…….(1 byte)
A char stores a single letter
What is actually stored is the binary sequence
corresponding to a letter’s ASCII code
You can either store a letter, or the numeric code for
the letter in a char
37
Check this out….
#include <iostream.h>
void main()
{
both a and c contain 65 or ‘A’
char a = 65, c = 'A';
cout << “ c = “ << c << endl;
cout << “ a = “ << a << endl;
}
Output…..
c=A
a = A (in other words, ‘A’ is same as 65)
38
Decimal ASCII Table
39
Character Input
Read 2 chars
char grade1, grade2;
cin>>grade1>>grade2;
cout<<“Grade 1 is ”<<grade1<<endl;
cout<<“Grade 2 is ”<<grade2<<endl;
NOTE
• white space ignored: type AB, A
B, A
(enter) B  same result
• Another interesting topic, character escape and
control sequences, p 53/54
40
Agenda
Review
C++ Standard Numeric Types
Arithmetic–way more than you want!
Character (char) data type
For Loop 
Syntax, Run-time and Logical Errors
41
Bored with single execution
programs?
Add a for loop to repeat your code several
times:
for (int k=1; k<=final_value; k=k+1)
{
statements to repeat
}
42
Example Looped code
Add a for loop to repeat your code several
times:
Or k++ for short
int main()
{
for (int k=1; k<=3; k=k+1)
Testing 1
{
Testing 2
cout<<“Testing”<<k<<endl;
Testing 3
}
}
43
Example Application (for challenge)
Calculate pay for 3 employees:
int hrs; double rate;
for (int emp=1; emp<=3; emp++)
{
cout<<“Enter hours & rate: ”;
cin>> hrs>> rate;
cout<<“Pay = $”<< hrs * rate <<endl;
}
See p57 to let user determine the number of iterations
44
Agenda
Review
C++ Standard Numeric Types
Arithmetic–way more than you want!
Character (char) data type
For Loop
Syntax, Run-time and Logical Errors 
45
Types of Errors
Syntax: an error in your C++ language/grammar (covered last week)
confuses compiler (The dog his paw)
forgetting a ;
misspelling a variable name datha=3.14;
Runtime: when you do something illegal during program execution
temp=0.0;
rate=1.0/temp; // dividing a number by zero –crash!
Logical (or Semantic): When you say something illogical
A paw ate his dog.
( Good grammar, illogical meaning)
avg = b + c / 2;
46
Tracking them down
Syntax—
double click on error message,
it takes you to line of code
Look at or above that line for possible errors
Runtime & Logical
You detect them by checking output against test plan
Pinpoint them by displaying variables during
intermediate steps (cout)
OR Use debugger to step through program, put watch on
variables
47
LIST OF KEYWORDS…..
asm
auto
bool
break
case
catch
char
class
const
const_cast
continue
default
delete
do
double
dynamic_
cast
else
enum
explicit
export
extern
false
float
for
friend
goto
if
inline
int
long
mutable
namespace
new
operator
private
protected
public
register
reinterpret
_cast
return
short
signed
sizeof
static
static_cast
struct
switch
template
this
throw
true
try
typedef
typeid
typename
union
unsigned
using
virtual
void
volatile
wchar_t
while
48
That’s a wrap !
What we learned today:
Data Types
Rules of Arithmetic
For loops
How to debug your program
49
A1) Answers to Scientific Notation
1234.56 = 1.23456 x 103
.03413= 3.413 e -2
6.78 x 107 = 67800000
5.32e-5 = 0.0000532
50
A2) Arithmetic Precedence
Evaluate the following
1+2 * 3 + 4
= 11
5+6/2*3
= 14
1 + 2 * (3 + 4) = 15
(7 + 5) / (2 * 3) = 2
51
A3) Answer:
int m, n; double x,y;
m = 3.0;
n = 12.7;
x = m;
x = x + 0.5
m = m + 1;
y = x + 1;
m
n
x
y
?
?
?
?
3
12
3.0
3.5
4
4.5
52
A4) Integer Division
int m, n; double x,y;
m = 10 / 3;
n = 30 / 7;
x = n * m;
y = 3 / 4 * x;
y = x * 3 / 4;
y = (x + 3) / 4;
m
n
x
y
?
?
?
?
3
4
12
0
9
3.75
53
A5) Arithmetic Assign Operator Table
START: int x=0;
Shorthand
Same as
Result
x+=5;
x*=2;
x/=5;
x-=2;
x+=10;
x*=3;
x%=8
x/=5;
x=x+5;
x=x*2;
x=x/5;
x=x-2;
x=x+10;
x=x*3;
x=x%8;
x=x/5;
5
10
2
0
10
30
6
1
54
Download