iBrad Apps iBrad Apps - 3 years ago 230
Objective-C Question

Simple Math iOS?

So in my app I am trying to do a simple math in one of my methods without using a ton of if/else statements.

So I have an integer named 'StartInt' which is at max 13. Now what I need to get is FinishInt an integer that will be the result of this pattern:

StartInt: 13 FinishInt: 1
StartInt: 12 FinishInt: 2
StartInt: 11 FinishInt: 3


etc... all the way down until StartInt is 1 and FinishInt is 13. Anyway how would I accomplish this? I know this must be simple but I am just not that great in Math! :)

Answer Source

All the way down until StartInt is 0 and FinishInt is 13. Anyway how would I accomplish this?

That won't quite work if startInt = 13 gives finishInt = 1 and you want a finishInt to increment 1 for each decrement of startInt. Check out the following table:

13   1
12   2
11   3
10   4
 9   5
 8   6
 7   7
 6   8
 5   9
 4  10
 3  11
 2  12
 1  13

So you're off by 1 at either the beginning or end of your sequence. Nevertheless, it looks like you want something like this:

(int) calculateFinish(int startInt)
{
    int finishInt = -1;
    if (startInt >= 0 && startInt <= 13) {
        finishInt = 14 - startInt;
    }
    return finishInt;
}

That'd give a value of 14 for finishInt when startInt = 0.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download