我是c ++的新手,我编写了一个函数,该函数将a和b作为输入并将a的次幂返回给b。我使用了模板作为函数的返回数据类型和数据类型。但是对于大量数字,它无法返回正确的结果。我尝试计算pow(2,50)并返回0。
template <class numeric_type>
numeric_type pow(numeric_type a, int b) {
numeric_type result = 1;
for (int i = 0; i < b; i++) {
result *= a;
cout << result << i << endl;
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
而在主内:
long long int powered = pow(2, 50);
cout << powered;
Run Code Online (Sandbox Code Playgroud)
是的,那行不通。数字类型“ 2”为int。使用'2LL'表示很长的整数。之所以不起作用,是因为2 ^ 50太大而无法存储在整数中(这是一个32位数字,但是您需要51位来存储2 ^ 50)
auto powered = pow(2LL, 50);