Here's a mathematical expression written in normal English. How would you rewrite it properly so that the computer could understand it. (This will involve putting in * and / at appropriate places).
What is the difference between the two numbers produced by this program?
#include <iostream.h>
void main ()
{
cout << "The first number is " << 7 - 3 * 2 << endl;
cout << "The second number is " << (7 - 3) * 2 << endl;
}
If you divide 20 by 4, you get the answer 5. The number 4 is 2 times 2 (written 2 * 2 on the computer), so if you divide 20 by 2 * 2, then you should get 5, yes? Try it and see ...
#include <iostream.h>
void main ()
{
cout << "This should be 5 : " << 20 / 2 * 2;
}
Oh dear! It didn't work! Why not? What could you do to correct this problem?
Here's another thing that goes wrong on my compiler - and may well go wrong on yours! Fractions are normally represented like this: 1/3 or 1/2, so a half is represented as "1 divided by 2" and a third is "1 divided by 3" etc. Try this in C++, however, and you may be in for a bit of a shock:
#include <iostream.h>
void main ()
{
cout << "This is one third : " << 1/3 << endl;
cout << "This is one half : " << 1/2 << endl;
}
Didn't work, huh? Oh well, never mind. What about this? If you divide 1 by 3 (giving one third) and then multiply it by 3 again, it should give 1 again. Huh! Fat chance! What does it give?
#include <iostream.h>
void main ()
{
cout << "This should be 1 : " << (1/3) * 3 << endl;
}