Obj-C: How to do basic math (Part II)
April 10, 2013 Leave a comment
On March 20th, I showed you how to do basic math in Objective-C. Now let’s take it a step further.
Suppose you need to add 4 numbers, and then divid that by 5. The problem says that you must add the numbers first before dividing them by 5.
A long time ago (when I wrote in BASIC) I learned a technique that even works today. You use the open bracket “(” and close bracket “)” to tell the computer what to calculate first. When that is done, then it will go on to the rest of the problem. Here’s how it works:
int a = 34;
int b = 12;
int c = 56;
int d = 87;
int answer = 0;
answer = (a + b + c + d) / 5;
Let’s break it down:
1. We initialize A – D with numbers for our math problem.
2. Since the answer variable will show the final answer, we initial it with the number zero (0).
3. The answer variable will first add what ever is in-between the brackets (), and then go on to divid that by 5.
The way to show the value of answer depends on your needs. You could use a NSLog statement or a label.
That’s it. Happy coding!