c++中的"^"符号问题—幂运算符与异或位运算符
今天在leetcode刷题时遇到求解2^31次方问题,于是使用int x=2^31;来计算,发现答案一直报错(2024/2032),不明其原因,经过测试代码后发现是"^"符号误用的问题。
原来在c++编译器中"^"符号不是幂运算符,而是异或位运算符,经过手动异或计算发现确实如此。
c++中的幂运算应使用pow()函数进行。
此乃题目之大坑,以后需留心,特此记录,以表警示!
#include <iostream> using namespace std; #include <string> #include <math.h> int main() { int x = 2 ^ 10; int y = 2 ^ (10); int z = (2 ^ (10)); int a = 2 ^ 3; cout << "x=" << x << endl; cout << "y=" << y << endl; cout << "z=" << z << endl; cout << "a=" << a << endl; }