In almost all of
our applications we need to construct arithmetic expressions using variables
declared in our program and constant numbers. This is done ( as
in algebra) using four different devices.
1)
Unary arithmetic operators:
Example
|
Equivalent
to
|
-
78.9
|
Unary
minus or additive inverse
|
k++
|
k
= k + 1 ( use k and then increase
it by one )
|
k--
|
k
= k - 1
|
++k
|
k
= k + 1 ( first increase it
by one then use it )
|
--k
|
k
= k - 1
|
2)
Binary arithmetic operators
( operations involving two numbers):
Operator
|
Effect
|
+
|
addition
|
-
|
subtraction
|
*
|
multiplication
|
/
|
division
|
%
|
remainder
after integer division
|
NOTE
1: The two numbers used in a binary operation must,
in general, agree in type. This is to say, both must be integers
or both float or both double, etc. However the compiler uses some rules
to proceed with operations of “mixed mode”. These rules may be
complicated, but we must remember the following:
int
& float |
both
are converted to float |
int
& double |
both
are converted to double |
float
& double |
both
are converted to double |
NOTE 2:
When we divide two integers the result is truncated to integer, consequently:
2 / 3 = 0
7 / 3 = 2
1 / 2 = 0
11 / 4 = 2
But,
2.0 / 3.0 = 0.666667
2.0 / 3 = 0.666667
2 / 3. = 0.666667
Writing 1
/ 2 when one wants to write 0.5 is a very common mistake
that many programers do. Please remember to add the period at
the end of both or at least one of the integers, to avoid the truncation
error.
3)
Parentheses
Using
parentheses we can group certain operations the way we mean to write
them. For example:
cost
= 7.2 + ( 4.0 / 0.5 ) will store 15.2 to the memory location
named cost, but
cost
= ( 7.2 + 4.0 ) / 0.5 will store
22.4 to cost .
4)
Library functions
We can use several
build in functions so that we can write expressions with sines, cosines,
exponents, logarithms, exponentials, etc. In order to use these functions
we must include the mathematics header by writing up on top of our program
something like: #include<math.h>. Look at your
book for a detailed description of the functions. Here we note only
two:
pow( base, exponent)
used to write powers, for example in order to write x5 we write POW(x,5).
exp( exponent
) used to write exponential, for example in order to write
e5x we write exp(5*x)
|