问题描述
问题
您好,这是我的第一个堆栈溢出问题。我正在使用位板来表示我的国际象棋引擎中的棋盘状态。目前我有一个像这样的位板类:
class bitboard {
public:
uint64_t Board = 0ULL;
void SetSquareValue(int Square) {
Board |= (1ULL << Square);
}
void PrintBitbaord() {
for (int rank = 0; rank < 8; rank++) {
for (int file = 0; file < 8; file++) {
// formula for converting row and colum to index
// rank * 8 + file
int square = rank * 8 + file;
if (file == 0) {
cout << 8 - rank << " " << "|" << " ";
}
cout << (Board & (1ULL << square)) ? 1 : 0;
cout << " ";
}
cout << endl;
}
cout << " ---------------" << endl;
cout << " a b b d e f g h" << endl;
//cout << "current bitboard: " << self << endl;
}
};
我也有这个枚举(位于实际文件中的类上方):
enum BoardSquare {
a8,b8,c8,d8,e8,f8,g8,h8,a7,b7,c7,d7,e7,f7,g7,h7,a6,b6,c6,d6,e6,f6,g6,h6,a5,b5,c5,d5,e5,f5,g5,h5,a4,b4,c4,d4,e4,f4,g4,h4,a3,b3,c3,d3,e3,f3,g3,h3,a2,b2,c2,d2,e2,f2,g2,h2,a1,b1,c1,d1,e1,f1,g1,h1
};
Testbitboard.SetSquareValue(e2);
关注:
8 | 0 0 0 0 0 0 0 0
7 | 0 0 0 0 0 0 0 0
6 | 0 0 0 0 0 0 0 0
5 | 0 0 0 0 0 0 0 0
4 | 0 0 0 0 0 0 0 0
3 | 0 0 0 0 0 0 0 0
2 | 0 0 0 0 4503599627370496 0 0 0
1 | 0 0 0 0 0 0 0 0
---------------
a b c d e f g h
与我想要的输出相比:
8 | 0 0 0 0 0 0 0 0
7 | 0 0 0 0 0 0 0 0
6 | 0 0 0 0 0 0 0 0
5 | 0 0 0 0 0 0 0 0
4 | 0 0 0 0 0 0 0 0
3 | 0 0 0 0 0 0 0 0
2 | 0 0 0 0 1 0 0 0
1 | 0 0 0 0 0 0 0 0
---------------
a b c d e f g h
我希望在 cpp 和位操作方面有更多经验的人可以解释为什么我会得到这个输出。虽然我对编程并不陌生,但我对 cpp 还是陌生的,而且我以前从来没有遇到过一些问题。
我的尝试
我看过以下视频。我曾尝试使用他们的类似功能的实现无济于事。
我能够获得的最大变化是值 4503599627370496 更改为不同但仍然不是我想要的输出。
解决方法
您违反了运算符优先级。 <<
的绑定比 ?:
强,所以直接打印按位表达式,条件表达式对流的结果状态执行,没有任何影响。
在您想要的条件表达式周围添加括号:大概是 cout << ((Board & (1ULL << square)) ? 1 : 0);
。