C / C++ Tutorial Part 5
Maths
The first use and the reason for computers is doing sums. This is no maths lesson and not a very long one. The main reason for this is to cover a little more on data types. In Part 1 I mentioned 3 basic types ; int, char and float. When it comes down to it these are just pieces of memory. The type tells the compiler what to do with these types.
If you want to count to
ten then a char will do. It is the smallest of
the data types and is good for -127 to +127. If you want bigger
numbers then an int is good for -32768 to +
32767. There is a little problem with the int
type, the size of it is different depending on the type of
computer and compiler you are using. Mostly what I just said is
true, an int is normally a 16 bit value. In a 32
bit windows application compiled with MS Visual C++ 5 an int
32 bits.
I tend to rely on an int being 16bits, I feel a
bit safer that way. If you want some more digits then try a long,
that's 32 on anything ( 64 bits for Win32 ). Oh yes, if you are
only interested in positive things then you can add unsigned
e.g.
unsigned int uiPositiveNumber = 0;
which is good from 0 to 255
If you want to do heavy maths ( stuff with decimal points ) then what you need is floats and doubles. A float has 32 bits of precision, a double has 64. A float can go down to 3.4 * (10**-38) to 3.4 * (10**+38) and thats a lot of points either way !
How to do maths ? Well the normal operators are available :
+ | plus |
- | minus |
* | multiply |
/ | divide |
% | remainder |
>> | shift right |
<< | shift left |
x = y + 4; adds 4 to 4
x = y - 4; takes 4 off 4x
x = y * 4; gives x = 4 times y
x = y / 4; gives x = y divided by 4
x = y % 4; gives the remainder of y divided by 4, for example 7 %
4 gives 3
x = y << 1 ; shifts y one bit to the left, makes y two
times bigger ( think binary )
x = y >> 1; shift y one bit to the right, makes y two times
smaller;
x = y << 2; shifts y two bits to the left - makes it 2*2
times bigger
We can do that. There are some other bits that make our life easier.
x = y++; sets x equal to y
then increments y
x = ++y; increments y then makes x equal to x.
That over with lets look at some functions that are available to us in ANSI 'C'.
This page hosted by Get your own Free Home Page