Objective c 在iOS中计算非整数指数
我一直在研究我的数学解析器,我逐渐意识到我使用的一些代码无法处理非整数的指数。我正在使用的代码位似乎可以与Objective c 在iOS中计算非整数指数,objective-c,c,math,exponent,shunting-yard,Objective C,C,Math,Exponent,Shunting Yard,我一直在研究我的数学解析器,我逐渐意识到我使用的一些代码无法处理非整数的指数。我正在使用的代码位似乎可以与int配合使用,但与double配合使用则不行 else if ([[token stringValue] isEqualToString: @"^"]) { NSLog(@"^"); double exponate = [[self popOperand] intValue]; double base = [[self pop
int
配合使用,但与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]];
}
"
使用Objective-C,我如何让5^5.5这样的东西正确评估?(6987.71242969)让我们为您完成工作:
double exponent = [[self popOperand] doubleValue];
double base = [[self popOperand] doubleValue];
[self.operandStack addObject:@(pow(base, exponent))];
让我们为你做这项工作:
double exponent = [[self popOperand] doubleValue];
double base = [[self popOperand] doubleValue];
[self.operandStack addObject:@(pow(base, exponent))];
Josh的回答是对的,我只是想补充一些关于在条件下使用浮动的内容:
double exponate = [[self popOperand] intValue];
exponate--;
while (exponate)
{
result *= base;
exponate--;
}
这可能导致无限循环,因为舍入错误
,而(expontate)
可能永远不会计算为false
。如果您使用双倍
或浮点
作为循环变量,请始终执行之类的操作,而(myFloat>0.0)
Josh的答案是正确的,我只想添加一些关于在条件下使用浮点的内容:
double exponate = [[self popOperand] intValue];
exponate--;
while (exponate)
{
result *= base;
exponate--;
}
这可能导致无限循环,因为舍入错误
,而(expontate)
可能永远不会计算为false
。如果您使用双倍
或浮点
作为循环变量,请始终执行while(myFloat>0.0)
之类的操作。您没有使用pow()
进行幂运算的原因是什么?直到现在我才需要使用它。我几乎是自学成才。但是谢谢,我不知道的另一个工具被添加到了工具箱中。@Joemilion同样,仅供参考,第二个操作数被称为“指数”,而不是“指数”。你为什么不使用pow()
进行指数运算呢?直到现在我才需要使用它。我几乎是自学成才。但是谢谢,我不知道的另一个工具被添加到工具箱中。@JoeMillion同样,仅供参考,第二个操作数被称为“指数”,而不是“指数”。别忘了\include
别忘了\include