Professional Documents
Culture Documents
Fundamental Data
Types
Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John
Wiley & Sons
Objectives
Arithmetic Operators
C++ has the same arithmetic operators as a calculator:
*
for multiplication:
a*b
(not a . b or ab as in math)
for division:
for addition:
for subtraction:
a/b
(not or a fraction bar as in math)
a+b
ab
Arithmetic Operators
Precedence
Just as in regular algebraic notation,
* and / have higher precedence
than + and .
In a + b / 2,
the b / 2 happens first.
(-(b * b - 4 * a * c) / (2 * a)
What is wrong with it?
-(b * b - (4 * a * c))) / 2 * a)
It is still not correct.
There are too many closing parentheses.
Roundoff Errors
This program produces the wrong output:
#include <iostream>
using namespace std;
int main()
{
double price = 4.35;
int cents = 100 * price;
// Should be 100 * 4.35 =
cout << cents << endl;
// Prints 434!
return 0;
}
435
Why?
8
Roundoff Errors
Math Functions
What about this?
b 1
100
Math Functions
11
Math Functions
Using the pow function:
r
1
100
------------------------------In C++
b + pow(1 + r / 100, n)
12
sqrt(x)
square root of x
sin(x)
sine of x (x in radians)
cos(x)
cosine of x
tan(x)
tangent of x
log10(x)
fabs(x)
Converting Floating-Point
Numbers to Integers
Formatting Output
Which do you think the user prefers to see on her gas bill:
Price per liter: $1.22
or
Price per liter: $1.21997
Formatting Output
Formatting Output
Formatting Output
Strings
Strings No Initialization
Needed
string response;
// literal string "" stored
Strings Concatenation
Use the + operator to concatenate strings;
that is, put them together to yield a longer string.
string fname = Ali";
string lname = Baba";
string name = fname + lname;
cout << name << endl;
name = fname + " " + lname;
cout << name << endl;
The output will be
AliBaba
Ali Baba
Strings Input
You can read a string from the console:
cout << "Please enter your name: ";
string name;
cin >> name;
When a string is read with the >> operator,
only one word is placed into the string variable.
For example, suppose the user types
AliBaba
gets
Baba
e
1
l
2
l
3
o
4
,
5
W
7
o
8
r l d !
9 10 11 12
String Operations
String Operations
Chapter Summary
1. A variable - a storage location with a name.
2. When defining a variable, we also specify the type of its value. Eg.
Int, float, double and etc.
3. Use comments to add explanations. The compiler ignores
comments.
4. An assignment statement - stores a new value suing operator =.
5. C++ supports the same four arithmetic operations as calculator (+, -,
/, *).
6. The C++ library defines many other mathematical functions.
7. String are sequences of characters.
8. Use operator + to concatenate strings and other member functions
to get the number of string and to extract substring.
QuickTime and a
TIFF (Uncompressed) decompressor
are needed to see this picture.