Objective-C math function - iphone

I want square the number.using pow(). So,pow(3,2) should be 9.But it showing 8 in my iOS Calculator application.here is my code:
else if([opertaion isEqualToString:#"sqrt"])
{
result=pow([self popOperand],[self popOperand]);
}
method
-(double)popOperand
{
NSNumber *operandObject = [self.operandStack lastObject];
if(operandObject)[self.operandStack removeLastObject];
return [operandObject doubleValue];
}
One thing,I'm newibe on iOS programming.
Thanks in advance.

I would imagine you're just thinking about your operands backwards. 2^3 == 8.

result=pow([self popOperand],[self popOperand]);
This statement is being executed from left to right ... so its calculating pow(2,3)
You can use
double x = [self operand];
double y = [self operand];
result = pow(x,y)

It seems like you are trying to pop the first number then the last. So, getPower(3,2) would come up as 2^3 instead. I would look at your stack and make sure that you are arranging them correctly.

Related

Weird behavior of for loop with multiple sprites in Sprite Kit

I am spawning 12 sprites to place in a game. Each sprite needs to have an original name. I am doing this by using a for loop. I have split the loop up to show you what is happening. So for the first couple of charges:
for (int i = -4; i <= 0; i++)
{
NSLog(#"i = %i", i);
[self spawnChargesWithNumber:i];
}
The NSLog tells me that i is -4, -3, -2, -1, 0. As it should. This calls the method spawnChargesWithNumber:i which looks like this:
- (void)spawnChargesWithNumber:(int)number
{
NSLog(#"number is %i", number);
_chargedBall = [[ChargedBall alloc] initWithImageNamed:[NSString stringWithFormat:#"ChargedBall%i", number]];
//code to make a random position
_chargedBall.position = CGPointMake(actualX, random);
_chargedBall.name = [NSString stringWithFormat:#"chargeNumber%i", number];
_chargedBall.zPosition = 15;
_chargedBall.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:13.0f];
_chargedBall.physicsBody.dynamic = YES;
_chargedBall.physicsBody.affectedByGravity = NO;
_chargedBall.physicsBody.mass = 0.1;
_chargedBall.velocity = CGPointMake(actualVelocityX, 0.0);
_chargedBall.physicsBody.categoryBitMask = chargeCategory;
_chargedBall.physicsBody.contactTestBitMask = playerCategory;
_chargedBall.physicsBody.collisionBitMask = playerCategory | selfCategory;
[self.map addChild:_chargedBall];
NSLog(#"You made charge with name %#", _chargedBall.name);
if (!_enemies) {
_enemies = [[NSMutableArray alloc] init];
}
[_enemies addObject:_chargedBall];
NSLog(#"you added %# to the array", _chargedBall.name);
}
I have an object called ChargedBall. The NSLog first tells me the number, which corresponds to i from above. Then it tells me I made charge (chargeNumberi) where it follows the same pattern. Then I add that chargedBall to an array. During the game if I collide with any of these, my NSLog from didBeginContact method tells me that I have contacted the proper charge. All is working as planned.
Since I actually have 12 charges and not 5 I have another for loop to show you. It is basically the same taking off where the other ended:
for (int i = 1; i <= 7; i++)
{
NSLog(#"i = %i", i);
[self spawnChargesWithNumber:i];
}
I did originally have these together, but I wanted to show you what was happening. After the call to spawnChargesWithNumber:i I get the rest of the charges. However, they are reversed! I don't get it. The NSLog still tells me the i, number, you created chargeNumberi, and added it to the array. I even NSLog the name of the image and it still corresponds. But chargeNumber7 shows picture 1, chargeNumber6shows picture 2, chargeNumber 5 shows picture 3, four is fine because there is an odd number of sprites to make, chargeNumber3 show picture 5, chargeNumber2 shows picture6 and chargeNumber 7 shows picture 1. So the entire thing is flipped. I have checked the pictures and they are all correct. This even happened when I had the for loop as just one loop, the positive charges were switched, but not zero to negative 4. Does anyone know why this would happen? I NSLog everything I could think of, I even changed the picture names, but nothing worked. If you need some more code from other places I can post, I am just so confused right now!
The problem has been solved. I really thought that I had programmed my for loop incorrectly. However, with the help of fuzzygoat and prototypical, I hardcoded everything, and used the debugger to find that all was as I intended. Therefore, prototypical suggested cleaning the derived data, as I had changed the image names after they had been imported to Xcode. I thought that cleaning the product did the same as deleting the derived data, but perhaps not. So thanks to everyone that looked and thanks to all that helped. You filled my brain with knowledge once again!

How to convert from text to number integer?

i have input only number from text field and i want to change it to integer. what code should i write in?
just say text field say for 10 and i want to take that 10 = x, x = integer. so if i use it for mathematic process a = x + 1 and display say 11. is there any chance? i hope you understand what i mean. thank you. i think both of you will answer this simple question but i not because im beginner. im a 3d design graphic switch 180 degree become xcode programming. BTW ive tried this before but it cant.
NSInteger number = [[txtBtn text] integerValue];
Edited :
i've got this error, local declaration of 'number' hides instance variable, pointed to number at result = (number * 2) - 1; and i put the code like this.
NSInteger number = [[txtBtn text] intValue];
result = (number * 2) - 1;
i dont know whats wrong.
Are you sure it's a TextField and not a UIButton you are trying to get the integerValue from?
[txtBtn text]
I created a TextField and a UIButton, and implemented your code:
- (IBAction)btnClicked:(id)sender {
NSInteger i = [[inputField text] intValue];
int result = (i*2)-1;
NSLog(#"%i", result);
}
the output results is correct.
ex: type 5, output in console is 9.

Implementing decimal instead of fraction, Calculator Xcode App

Ive scoured everywhere and haven't found a situation similar to mine.. New to Xcode/Objective C, I am putting together a dual purpose (fraction/decimal) calculator app. Ive found some good stuff on the fractions, and have them calculating correctly. However the decimal is a different story. I can get it to appear with this:
-(IBAction) pressDecimal
{
NSRange range = [display.text rangeOfString:#"."];
if ( range.location == NSNotFound ) {
display.text = [display.text stringByAppendingString:#"."];
}
or this:
-(IBAction) pressDecimal
{
[displayString appendString: #"."];
display.text = displayString;
}
The latter works great, to DISPLAY it on the calculator. I try to read it in as a slot, a double, and i just can't seem to read it in properly... here is how i get the digits in:
- (void) workNums: (int) nums
{
currentNumber = currentNumber * 10 + nums;
[displayString appendString:
[NSString stringWithFormat: #"%i", nums]];
display.text = displayString;
}
//uses tags from attribute inspector (decimal tagged 10)
-(IBAction)pressNum:(UIButton *)sendIT
{
int nums = sendIT.tag;
[self workNums: nums];
}
Ive looked everywhere, tried changing from floats to doubles ( i can get it to display 0.00's when i play with them) also here is my method to converting the ANSWER that is a FRACTION to a DECIMAL..which works great too:
- (double) convertToNum
{
if (denominator != 0)
return (double) numerator / denominator;
else
return NAN;
So again, cleanly stated... How may I get Objective C to see the decimal inputed in the app, and display the answer as a decimal properly.. am i screwed because i started this a mainly a fraction calculator? Thanks from a noob that moved from BASIC to Objective C
EDIT 4/27/12 ***
(new to Stack - but please read my comment below.. i am looking to find out why i can't read decimals into my program... I've tried changing from ints (which i know won't work) and doubles and floats, but all i get is 0.00 on user input when running this all as doubles:
-(IBAction)pressNum:(UIButton *)sendIT
{
int nums = sendIT.tag;
[self workNums: nums];
}
- (void) workNums: (int) nums
{
currentNumber = currentNumber * 10 + nums;
[displayString appendString:
[NSString stringWithFormat: #"%i", nums]];
display.text = displayString;
}
So the goal is to be able to CALCULATE a user inputted decimal number...any suggestions on a if/else situation as these numbers build up in an accumulator / and a double for currentNumber and get turned into numerators/denominators later down the line..(which is probably my issue, but it shouldn't be hard, but I'm making it hard, to use a BOOL or something to say, hey..this isn't a fraction, its a decimal - so lets do this - PLEASE HELP!! GOING NUTS!
I may be thinking this is much simpler than it is, but: if you already have a string like #"3.14" in displayString then you can convert that directly to a double:
double doubleValue = [displayString doubleValue];
Would that not be enough to get the double value and perform calculations?

Is there a shorthand way to get a float from an array?

I'm a beginner with iPhone dev in Objective C and one thing I find I'm doing quite a lot is getting floats (and ints) in and out of various NSArrays
float myFloatValue = [(NSNumber *)[myArray objectAtIndex:integerSelector] floatValue];
I understand that I need to do this boxing because a float (or int) isn't a pointer and the NSArray accepts only pointers.
I'm just wondering if there a little bit of syntactic sugar to shorten this line of code - mostly because when I have a couple of arrays and I'm looping over them to do some processing I find that the lines start getting massive and I have to break out the lines that extract the number form the array just to make the code readable - then I have a lot of gumph lines that tend to make the logic harder to follow.
In a language like C# I would write something like
float myResult = myArray[i] + someOtherArray[i+1];
(ok - that's probably a pretty dumb line of code - but syntactically it's quite clean, I guess because .net is doing the boxing implicitly where I can't see it)
in objective C I find myself writing:
float myFloatValue = [(NSNumber *)[myArray objectAtIndex:i] floatValue];
float myOtherFloatValue = [(NSNumber *)[someOtherArray objectAtIndex:i+1] floatValue];
float myResult = myFloatValue + myOtherFloatValue;
I'm just wondering if I'm missing a trick here by typing it all out longhand. Should I be using an alternative to NSArray? Is there a shortcut for the boxing/unboxing?
Or I guess, should I just get used to it and stop whinging ;)
You can create a category:
#class NSArray (FloatHelper)
- (float) floatAtIndex:(NSUInteger)i;
#end
#implementation NSArray (FloatHelper)
- (float) floatAtIndex:(NSUInteger)i {
return [[self objectAtIndex:i] floatValue];
}
#end
(Untested and has no error handling, which, obviously, is not a good idea.)
Then it could be used as follows:
float a = [array floatAtIndex:1];
I don't think there is any shorthand for that, by the way
float myFloatValue = [[myArray objectAtIndex:i] floatValue];
is legal.
Unfortunately Objective-C doesn't support Auto-Boxing.
For more info please visit to link -Aotoboxing in objective c?
You can create a category, a function or a macro to do this with less verbose code.
But if you are doing this in a loop that consumes significant CPU time (as determined by profiling with Instruments), you should consider using a C array instead, which can be accessed using far less CPU cycles, thus conserving the users battery life. If you are touching the same elements multiple times, it might even be an optimization to copy all these floats from an NSArray to a plain C array of floats before doing your computation loop.
Why don't you create a macro,
#define _floatValue(array, index) [(NSNumber *)[array objectAtIndex:index] floatValue]
use it,
float myFloatValue = _floatValue(myArray, i);
float myOtherFloatValue = _floatValue(someOtherArray, i+1);
float myResult = myFloatValue + myOtherFloatValue;
and just stop bothering yourself?

Store user input, calculate and show in the end

I'm writing a program that calculates input a user gives, simple numbers. 2, 4, 7, 10, 12 and so on.
I need the program to store these inputs (that come in from different textfields) somehow. Use them in an internal equation, and then show them to the user in the end.
How do I do this? Please take note that I'm rather new at programming.
I know how to define textFields, do a calculate IBAction , and I've tried creating a -(void)calculate, which works, but only on 1 input. When I execute the following code, with input from 6 textfields instead of 3 (which are used in the first line (resultOne)) it gives me the wrong numbers. But I still need a better way of doing this.
-(void) calculate{
weightOne = [v1Text.text floatValue]/2;
weightTwo = [v2Text.text floatValue]/2;
resultOne = [m1Text.text floatValue] * weightOne + [s1Text.text floatValue] * weightOne;
resultTwo = [m2Text.text floatValue] * weightTwo + [s2Text.text floatValue] * weightTwo;
_resultTotal = (resultOne + resultTwo) / (weightOne + weightTwo);
NSString *resultString = [[NSString alloc]
initWithFormat: #"%.2f", resultOne];
resultLabel.text = resultString;
[resultString release];
}
I know that the above code outputs resultOne, but this is just for my own testing, to know that the equation works. But I would really like to start all fresh, since I don't believe that the above code is suitable for what I need it to do.
Please bare in mind that I am a beginner, and explain a little more, than just showing me some code.
I look forward to any help you can give me.
EDIT! - BELOW IS NEW CODE
-(IBAction) calculate:(id)sender {
weightOne = 1;
weightTwo = 0.75;
weightThree = 0.50;
mOne = [m1Text.text floatValue];
mTwo = [m2Text.text floatValue];
sOne = [s1Text.text floatValue];
sTwo = [s2Text.text floatValue];
resultOne = (mOne*weightOne) + (sOne*weightOne);
resultTwo = (mTwo*weightTwo) + (sTwo*weightTwo);
_resultTotal = (resultOne + resultTwo) / (weightOne*2 + weightTwo*2);
NSString *resultString = [[NSString alloc]
initWithFormat: #"Gennemsnit %.2f", _resultTotal];
resultLabel.text = resultString;
}
I decided to change my code, in order to easily calculate the input. Now I have another question.
Is it possible to save this equation in some way, so I can reuse it as many times as I want, without having to type the code again and again and again.
First of all calculate can be your IBAction method which will be called when tapped on the button. So change the prototype to -(IBAction)calculate:(id)sender.
Next if you are able to have outlets for the text fields, then there is no harm and absoulutely no difficulty in getting the text entered in them.
Few things you can do are to validate for correct input. [v1Text.text floatValue] is right expression for getting the numbers from text. You can also have a look at intvalue.
Now once you have done your computation, you can use the reference to the label/textfield where you want to display the result.
You can change that label exactly the way you did in your code.