简体   繁体   English

在目标c中使用长数进行pow操作

[英]pow operation wih long numbers in objective c

I am trying to make the operation pow(49999994,13) which results 1.220701e+100. 我正在尝试使操作pow(49999994,13)结果为1.220701e + 100。 But when i do in objective ci got the result -9223372036854775808. 但是当我在客观ci中执行时,结果为-9223372036854775808。 How can I do this operation in Objective-C correctly? 如何在Objective-C中正确执行此操作?

There is no pow operator in Objective-C, so use C or NSDecimalNumber (preferred). 在Objective-C中没有pow运算符,因此请使用C或NSDecimalNumber(首选)。

pow 战俘

NSLog(@"%f",(double)pow(49999994,13));        // OK 12207012207044960421719...
NSLog(@"%f",(long long int)pow(49999994,13)); // WRONG -9223372036854775808

-92233... results from using a long long int instead a double . -92233...是由于使用long long int而不是double导致的。

NSDecimalNumber NSDecimalNumber

As noted by Martin R, the proper way to do it in Objective-C is NSDecimalNumber , which produces as many accurate digits as possible followed by zeros. 正如Martin R所指出的,在Objective-C中完成此操作的正确方法是NSDecimalNumber ,它产生尽可能多的准确数字,后跟零。

    NSDecimalNumber *n = [NSDecimalNumber decimalNumberWithString:@"49999994e0"];
    n = [n decimalNumberByRaisingToPower:13];
    NSLog(@"nsdecimal %@",n);

Compare the results: 比较结果:

 accurate 12207012207044960931467189309843359073812548192494216675520514965298161665721254575494908505339305984
nsdecimal 12207012207044960931467189309843359073800000000000000000000000000000000000000000000000000000000000000
      pow 12207012207044960421719677106210881027530912788496417091073101786581413645039745611250537465292783616.000000

If you see the method declaration of pow() it is something like this : 如果看到pow()的方法声明,它是这样的:

double pow(double, double);

And you saved the result into long int or you printed using integer(s) specifiers, resulting in exceeding the max limit of long int . 然后将结果保存到long int或使用整数说明符进行打印,结果超出了long int的最大限制。

You can use it as : 您可以将其用作:

 double result=pow(49999994,13);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM