Monday, June 15, 2015

3.2 Basic Mathematical Operations

Now if you have not read the first post before this, I think you should be reading that first to install the relevant platform for you to practise and test out C++. This post will be about basic mathematical operations in the language C++.


As you can see from the above image, we can compute basic mathematics using the various operators: '+', '-', '*' and '/'. One operator that we might not be too familiar with will be '%' - this percentage sign actually gives us the reminder of the two numbers. For instance, in the example above: we keyed in '7 % 3'. That is to say, the percentage sign will give us the reminder of 7 divided by 3. So let us run the above code and see if it works.

Do you remember how to run you code in xcode? Yes, the 'command' + 'r' button on your keyboard.


Now, note the differences in answer for line 1 and the rest of the lines. For line one, we are able to see the mathematical expression. Can you guess why is that so?

I think most of you would be able to guess it right from our code. In the first line of code for our computation includes the string: "3 + 6 = " while the rest of the code did not include the string.

Let me guess your next question: What does 'endl' do?

What if I refuse you answer you? What can you do to find out what 'endl' means? Maybe we can try removing 'endl' from the first line.


So if you have remove 'endl' from the first mathematical expression, your code will look something like the above. Let's now run it and see what happens?


You can almost spot the mistake immediately. What's with the first line? 3 + 6 is not equal to 93. Even a kid knows that. So why is this happening?

Apparently, the 'endl' tells the computer to print the answer for the next expression in the next line. Hence, when you remove the 'endl' from the first expression, the computer prints the answer to the second mathematical expression on the same line as the first resulting 9 and 3 to stick together. This gives us the misconception that the computer program is making an error in calculation when we are the one who did not instruct the computer to print the next line.

It's getting late today. Let me stop here for today. I might do up a more in-depth tutorial about operations the next time round. Feel free to try out on your own when you have the time.

Have fun learning!

No comments:

Post a Comment