Arithmetic Operator:

advertisement
Lecture Note 3
Ch.3 (p96-p122)
Arithmetic Operator:
Some of the arithmetic operators are:
+
*
/
%
Modulus:
The division of two integer values can produce rather strange results. For
example, the Expression 15/2 yields the integer result 7. Because integers cannot contain
a fractional part, a value of 7.5 cannot be obtained. The fractional part obtained when two
integers are divided, that is the remainder is always dropped (truncated). Thus, the value
of 9/4 is 2, and 18/3 is 5.
Often however, we may need to retain the remainder of an integer of an integer
division. To do this C++ provides an arithmetic operator having the symbol %. This
operator, called the modulus operator, captures the remainder when an integer number is
divided by an integer. Consider the following g examples:
9 % 4 is 1
(that is, the remainder when 9 is divided by 4 is 1)
17 % 3 is 2
(that is, the remainder when 17 is divided by 3 is 2)
15 % 4 is 3
(that is, the remainder when 15 is divided by 4 is 3)
5 % 2.3 is error (both operands must be integer)
Consider the following statements:
alpha = num + 6;
alpha = num / 2;
num = alpha * 2;
num = 6 % 2;
alpha = alpha + 1;
num = num + alpha;
Order of Precedence:
In C++ the following order of precedence is followed:
*,
/,
%,
+,
Note that the operators *, /, and % have the same level of precedence. Similarly,
the operators + and – have the same level of precedence. When operators have the same
level of precedence, the operations are performed from left to right. To avoid confusion,
you can use parentheses to group arithmetic expressions. For example, using the order of
precedence rules,
3*7–6+2*5/4+6
means the following:
(3 * 7) – 6 + ((2 * 5) / 4) + 6
1
Increment and Decrement Operators:
Now that you know about C++ operators, it’s time that you learn about two more
important operators that you will be using quite often. Those are Increment(++) and
Decrement(--) operators.
Suppose count is an int variable. The following statements:
count = count + 1;
count = count – 1;
increments/decrements the value of count by 1. Now the following statements will also
increment/decrement the value of count by 1:
count++;
count = count++;
count--;
count = count--;
Note that you can write count++ or ++count and count-- or --count.
Type Coercion and Type Casting:
Type coercion is the implicit (automatic) conversion of a value from one data type
to another. Let’s take the following example:
float gross_income;
float tax;
int netincome;
netincome = gross_income – tax;
if gross_income is 50.30 and tax is 10.78 your netincome should be 39.52. But when
39.52 is stored into netincome only 39 is stored. .52 is truncated. We can call this
scenario type coercion.
Type Casting is the explicit conversion of a value from one data type to another;
also called type conversion. Let’s take the following example;
int sum;
int count;
float average;
average = float(sum) / float(average);
This statement gives floating-point division instead of integer division. So if sum
is 13 and average is 2 the value 6.5 is stored in average. Without the type casting only 6.0
would have been stored in average.
We can also use the cast operator. It has the following form:
2
static_cast<dataTypeName>(expression)
Consider the following examples:
static_cast<int>(7.9); is 7
static_cast<double>(5+3); is 8.0
cout<< “Sum of 5 and 3 is:”<<static_cast<double>(5+3); should print/display 8.0.
In the following example, what happens to the value of L after the execution of the
following code? What output would you see from the following code?
float L;
L = 8.5 + 3.0;
cout<<"L is: "<<L<<endl;
cout<<"Let’s do Static Casting: "<<static_cast<int>(L)<<endl;
cout<<"L is: "<<L<<endl;
Library Functions:
We know that C++ comes with a lot of predefined functions, which are written by
the vendor’s programmers. A collection of functions is called a library. Examples of
some libraries are iostream, iomanip, string etc. You have seen reference of them in
#include<iostream> or #include<string> form. Now we are going to learn how to use
functions that can be found in a library.
By this time you have already used two libraries. They are iostream and string.
You have used cout, cin, endl manipulators from iostream library by using directive such
as #include<iostream>. You declared and used string data type, which were made
available by using directives such as #include<string>.
We see that first thing we need to do to use a function from a library is to declare
that library name. We do that by using directives such as #include<library>. Consider the
following code. It performs some mathematical operations such as cos, random number
generation etc:
#include<iostream>
#include<cmath>
#include<string>
#include<cstdlib>
//We use cin, cout, endl, manipulators which are defined in this library
//We use functions such as log, sin, cos which are defined in this library
//We use data type string which is defined in this library
//We use function such as rand from this library
using namespace std;
int main()
{
string name;
float angle;
int random_number;
cout<< “Please enter your name”<<endl;
3
getline(cin, name);
//will allow user to enter space in between his first
//and last name
cout<< “Please enter the angle”<<endl;
cin>>angle;
angle = cos(angle); //will return cos of angle
cout<< “Hello ”<<name<< “ cos of your angle is: ”<<angle<<endl;
cout<<rand()<<endl; //will generate a random number
random_number = rand();
//will generate a random number and load it to
//random_number variable
return 0;
}
From the above programming example we see that by using functions from
predefined libraries our job to find cos, generate random number have become very easy.
All we needed to know was the library and the function name from that library. In the
future you will learn how to write your own library and use it in your program.
Formatting the Output:
When you program your job is more than getting the correct output. You always
have to make sure that your output is meaningful and easily readable by your user. In
other words you have to make sure that you always format your output so that anybody
can understand the information you are trying to convey.
In C++ we use output manipulators to organize our output. Some of the examples
of manipulators are setprecision, fixed, showpoint, setw, flush, setfill, left and right etc.
fixed:
Sometime your system may display a big floating number with scientific notation.
For example the number 123456789.5 may be printed as 1.234567E+08. To avoid this
you can use the manipulator fixed to force all subsequent floating-point output to appear
in decimal rather than scientific notation.
cout<<fixed<< 3.8 * x;
setprecision:
setprecision is used to format float data type. By using setprecision we can
specify how many decimal places we want our output to have. setprecision is a member
of iomanip library. So you need to define #include<iomanip> at the beginning of your
program.
cout<< setprecision(3)<<netincome<<endl; //displays your net income with 3
//decimal places
showpoint:
Sometimes if the number is a whole number your system may not print a decimal
point. For example 95.0 can be printed as 95. To force your system to print the decimal
point to be displayed you can use showpoint.
4
cout<<showpoint<<floatVariable;
cout<<fixed<<setprecision(2)<< “Tax is $”<< price * 0.05<<endl;
setw:
setw lets us control how many character positions the next data item should
occupy when it is output. setw is only for formatting numbers and strings not char data.
Let’s look at an example:
ans = 33;
num = 7132;
The following output statement produces the output shown to its right:
cout<<setw(4)<<ans<<setw(5)<<num<<setw(4)<< “Hi”;
_ _ 3 3_7132_ _ Hi
setw is a member function of the library iomanip.
Do the table on page 119 from the book.
setfill:
Recall that, in the manipulator setw, if the number of columns specified exceeds
the number of columns required by the expression, the output of the expression is right
justified and the unused columns to the left are filled with spaces. The output stream
variables can use the manipulator setfill to fill the unused columns with a character other
than a space. An example to use the manipulator setfill is:
cout<<setfill(‘#’);
sets the fill character to # on the standard output device. Setfill is a member of the library
iomanip. Consider the following example:
#include<iostream> //We use cin, cout, endl, getline from this library
#include<iomanip> //We use manipulators such as setfill, setprecision from this library
using namespace std;
int main()
{
int x = 15;
int y = 7634;
cout<<setfill(‘*’);
cout<<setw(5)<<x<<setw(7)<<y<<setw(8)<< “Warm”<<endl;
return 0;
}
This code will output: ***15***7634***Warm
left:
Sometimes if you want to left-justify your output in setw you can use the left
manipulator. Consider the following example:
5
cout<<left;
cout<<setw(5)<<x<<setw(7)<<y<<setw(8)<< “Warm”<<endl;
will produce output: 15***7634***Warm****
Additional string Operations:
To be continued (from the book Page 122).
6
Download