在输入文件中将有两个数字,在1≤n,m <100之间。 我应该显示m到电源n。当我使用POW(x,y)函数时,它无法计算EX ::: 12的大整数到POWER 23通常应该显示6624737266949237011120128,但我的代码显示负数。任何人都可以解决这项运动吗?

有帮助吗?

解决方案

在不使用外部库的情况下,这不是很困难的。将数字的数字存储在向量中并按数字乘以数字(如您在纸上所做的)。

Example:

power(12,23):

Store as start->1->2->end

step 1 result: start->1->4->4->end
step 2 result: start->1->7->2->8->end

and so on...
.

其他提示

你可以展示你的源代码吗? 使用double足以存储结果 下面是我的测试代码参考:

#include <iostream>
#include <cmath>

using namespace std;

int main (int argc, char *argv[])
{
    double result = pow (12, 23);
    cout.precision (26);
    cout << "Result: " << result << endl;
}
.

Try to store your base in a long double before calling pow :

long double base = 12;
long double result = pow(base, 23);

It is not required since C++11 though, you can get a good approximation like this :

#include <iomanip>
#include <iostream>
#include <cmath>

int main ()
{
    std::cout << std::fixed << std::setprecision(0) << pow(99, 99) << std::endl;
}

Output :

369729637649726802192985226395427290145296428445515959701359650120802601667133273280053721002700400354392780458116125965728631706472588849812738072765460822138161108630185181415759762204338929270784

But it is an approximation, for instance Python2 code print 99 ** 99 outputs this :

369729637649726772657187905628805440595668764281741102430259972423552570455277523421410650010128232727940978889548326540119429996769494359451621570193644014418071060667659301384999779999159200499899

To get an exact result in C++, you should look at some BigInt libraries.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top