Reputation: 17
I am trying to develop a starter app just to get used to some of the utilities of Xcode and iOS development. I am trying to create an app that will solve the quadratic equation. I have tried to add this code under the "Calculate " button action. First I had "Calculate" just add the three inputs together. Now I am trying to make it solve the equation. This is what I put so far.
-(IBAction) Calculate {
float x = ([A.text floatValue]);
float y = ([B.text floatValue]);
float z = ([C.text floatValue]);
total.text =[NSString alloc]initWithFormat:@"%.2f", -y+sqrtf(y*y-4*x*z)/2*x;
}
I know this is not the full equation, but this is what I have so far. The error I receive is to add a bracket where the semicolon is. How to make this more effecient? I wanted to create a solveEquation()
function but I ran into problems. What can I do?
Upvotes: 0
Views: 892
Reputation: 385590
You need more brackets!
total.text = [[NSString alloc]initWithFormat:@"%.2f", -y+sqrtf(y*y-4*x*z)/2*x];
The brackets indicate that you're sending an Objective-C message. For each message you send, you'll need one pair of brackets. Let's break it down like this:
NSString *uninitializedString = [NSString alloc];
NSString *initializedString = [uninitializedString initWithFormat:@"%.2f", x+y+z];
total.text = initializedString;
In the first line, we send the alloc
message to the NSString
object, which is actually a class object that knows how to allocate instances of NSString
. But it does not initialize the instances. It pretty much just allocates the memory for them.
In the second line, we send a message to this allocated-but-uninitialized instance of NSString
, telling it to initialize itself by formatting the template %.2f
. This message returns an initialized instance of NSString
.
Finally, in the third line, we use that initialized instance of NSString
.
Obviously, it would be tedious to always need an intermediate variable to hold an allocated-but-not-initialized object. So we eliminate it by taking the result of the first message, and sending a message directly to it:
total.text = [[NSString alloc] initWithFormat:@"%.2f", x+y+z];
Upvotes: 3
Reputation: 138051
You need more brackets. The correct syntax is [object message]
, and since [NSString alloc]
returns an object, you need [[NSString alloc] initWithFormat:@"%.2f", -y+sqrtf(y*y-4*x*z)/2*x]
(initWithFormat:
being another message).
Upvotes: 3