math - Objective-C Exponent Method Failure -


for practice decided make exponent method handles things if wanted 20^2 20*20 of course should come out 400. here method:

 #import "math.h"   @implementation math   +(double)exponent:(double)n :(int)e{      double product = n;      for(int x=0; x<e; x++){          product *= product;      }      return product;  }   @end 

so use so:

         double product = [math exponent:20 :2];          nslog(@"product = %g",product); 

strangely comes out 160000 every time rather 400. have done incorrectly?

i understand there no exponential operator in objective-c '^' for. used 20^2 came out 22. why this?

thanks y'alls help!

your loop wrong.

double product = n; for(int x=0; x<e; x++){     product *= product; } 

original value: product = 20.

x=0; product = product * product. (that product = 20 * 20 = 400)

x=1; product = product * product. (that product = 400 * 400 = 160000)

your loop should be:

double product = n; for(int x=1; x<e; x++){     product *= n; } 

note loop starts x = 1 , product product *= n; way: product = 20.

x=0; product = product * e. (that product = 20 * 20 = 400)


Comments

Popular posts from this blog

user interface - How to replace the Python logo in a Tkinter-based Python GUI app? -

objective c - Greedy NSProgressIndicator Allocation -

how to set an OCR language in Google Drive -