Let library code do the work for you:
double exponent = [[self popOperand] doubleValue];
double base = [[self popOperand] doubleValue];
[self.operandStack addObject:@(pow(base, exponent))];
Domanda
I've been working on my math parser a bit, and I have come to realize that a bit of code I'm using is unable to handle an exponent that is non-interger. The bit of code I'm using seems to work just fine with an int
, but not with a double
.
else if ([[token stringValue] isEqualToString: @"^"])
{
NSLog(@"^");
double exponate = [[self popOperand] intValue];
double base = [[self popOperand] doubleValue];
result = base;
exponate--;
while (exponate)
{
result *= base;
exponate--;
}
[self.operandStack addObject: [NSNumber numberWithDouble: result]];
}
' Using Objective-C, how do I make something like 5^5.5 evaluate properly? (6987.71242969)
Soluzione
Let library code do the work for you:
double exponent = [[self popOperand] doubleValue];
double base = [[self popOperand] doubleValue];
[self.operandStack addObject:@(pow(base, exponent))];
Altri suggerimenti
Josh's answer is right, I just wanted to add something about using floats in conditions:
double exponate = [[self popOperand] intValue];
exponate--;
while (exponate)
{
result *= base;
exponate--;
}
This can lead to an infinite loop because of rounding erros while (exponate)
might never evaluate to false
. If you are using doubles
or floats
as loop variables, always do something like while (myFloat > 0.0)