我要解决的问题是:
实现pow(x,n),用于计算x的n次方(Leetcode问题50)
我有以下代码:
当运行测试用例
为什么我会遇到这个问题,如何解决?谢谢提前帮忙。
实现pow(x,n),用于计算x的n次方(Leetcode问题50)
我有以下代码:
class Solution {
public:
double myPow(double x, int n) {
if (n == 0) {
cout << "in last";
return 1;
} else if (n < 0) {
x = 1 / x;
return myPow(x, -n);
} else if (n % 2 == 0) {
double y;
cout << "in even";
y = myPow(x, n / 2);
cout << "y is ";
cout << y;
return (y * y);
}
else {
cout << "in odd";
double j = myPow(x, n - 1);
cout << "j is ";
cout << x * j;
return (x * j);
}
}
};
当运行测试用例
x=1.00000
和n = -2147483648
时,出现错误:runtime error: negation of -2147483648 cannot be represented in type 'int'; cast to an unsigned type to negate this value to itself (solution.cpp)
为什么我会遇到这个问题,如何解决?谢谢提前帮忙。