Could someone tell me what I'm doing wrong please.
I'm writing a simple app which will work out a sequence form any formula you enter.
The code for working out a quadratic sequence goes like this:
Code:
int i;
for (i=1; i<=12; i++) {
sequenceValues[i-1] = (nNum*(i*i))+cNum;
}
That works fine, but in this app the user inputs the exponent for n^whatever.
That works for the case of n2, but what if the user wanted to calculate n3 or n4? Sure I could use switch statements, but that's not very efficient, and also wouldn't calculate n1.5... so I though how about this:
Code:
int i;
for (i=1; i<=12; i++) {
sequenceValues[i-1] = (nNum*(i^userExponentValue))+cNum;
}
Turns out, if I use i^variable, I get really random results, for example:
n3 with that code =
2, 1, 0, 7, 6, 5, 4, 11
when really it should be (using i*i*i) =
1, 8, 27, 64, etc...
So, my simple question is what is the correct usage of ^ in objective-c... or is there another way to do it
Could someone tell me what I'm doing wrong please.
I'm writing a simple app which will work out a sequence form any formula you enter.
The code for working out a quadratic sequence goes like this:
Code:
int i;
for (i=1; i<=12; i++) {
sequenceValues[i-1] = (nNum*(i*i))+cNum;
}
That works fine, but in this app the user inputs the exponent for n^whatever.
That works for the case of n2, but what if the user wanted to calculate n3 or n4? Sure I could use switch statements, but that's not very efficient, and also wouldn't calculate n1.5... so I though how about this:
Code:
int i;
for (i=1; i<=12; i++) {
sequenceValues[i-1] = (nNum*(i^userExponentValue))+cNum;
}
Turns out, if I use i^variable, I get really random results, for example:
n3 with that code =
2, 1, 0, 7, 6, 5, 4, 11
when really it should be (using i*i*i) =
1, 8, 27, 64, etc...
So, my simple question is what is the correct usage of ^ in objective-c... or is there another way to do it
Thanks for help in advance,
Alex
You want the function pow(x,y).
It raises x to the y power, where x and y are both floating point numbers.
Note that it is MUCH slower than repeated multiplication, so if you are doing thousands or millions of calculations, it is faster to special-case integer powers and use repeated multiplication instead. I would use a for loop rater than a a case statement however, to make the code cleaner.
Check out this password generator app that shows various techniques including using a data container singleton object to share data between objects in your project.