How to use exponents with Objective-C in Xcode

Let's say I want to calculate the expression 3x^3-5x^2 with a variable x that has a valuable of 5. The ^ is 'to the power of' or the exponent. How do I use exponents in code in Objective-C? Thanks.

iMac 27" Core i5 Mid-2010 Model

Posted on Jul 22, 2011 9:57 PM

Reply
7 replies

Jul 23, 2011 4:24 AM in response to Chief Tarun

//Here are three files that were used to solve your problem. I hope it helps!


#import <Foundation/Foundation.h>



@interface XtoPowerOfY : NSObject {

int x;

int y;


intanswer;

}

@property int x, y, answer;

- (void)displayXtoY;


@end


#import "XtoPowerOfY.h"



@implementation XtoPowerOfY

@synthesize x, y, answer;


-(void)displayXtoY

{


answer = pow(x,y);


NSLog(@"x to the Power of y = %d", answer);

}


#import <Foundation/Foundation.h>

#import "XtoPowerOfY.h"


int main (int argc, const char * argv[]) {

NSAutoreleasePool * pool = [[NSAutoreleasePoolalloc] init];


// insert code here...


XtoPowerOfY *z = [[XtoPowerOfYalloc]init];

z.x = 2;

z.y = 3;


[z displayXtoY];


[z release];

[pool drain];

return 0;

}

Jul 23, 2011 7:31 PM in response to Chief Tarun

answer = pow(x,y);//this line find the value of x raised to the power of y.


From the above line, the value of y would be 2. That would produce x^2. You would then have to add another two variables, e.g.

int y = 2;

int p = pow(q,y);// this line would then produce q raised to the power of 2.


You can also copy my code into the appropriate files and run the program to see how it operates. I tested it and it runs without errors.


I hope this solves your problem.

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

How to use exponents with Objective-C in Xcode

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.