尝试计算二维数组中的特定字符,但计算整个数组
Trying to count specific char in 2D array, but entire array is counted instead
我正在尝试计算特定字符在二维数组中出现的次数。问题是它正在计算数组中的所有字符。我不知道为什么。
int P = 0;
int p = 0;
int R = 0;
int r = 0;
int N = 0;
int n = 0;
int B = 0;
int b = 0;
int Q = 0;
int q = 0;
for (int x = 0; x < BOARD_SIZE + 1; x++) // This side is 9
{
for (int y = 0; y < BOARD_SIZE; y++) // This side is 8
{
char temp = ' '; // Tried using temp as pass through, but no difference
temp = chessBoards[x][y];
// cout << temp; // When this is on it prints each element of the array list in order with a number beside it
if (temp = 'P') // This is just one character I am trying to count
{
++P; // It increments for every character so it's not checked properly
}
}
}
cout << P << endl << endl; // This is what I am using to test output
将if (temp = 'P')
更改为if (temp == 'P')
这只是一个错字..
if (temp = 'P')
您正在使用赋值运算符而不是比较。
要测试是否相等,请使用 == 而不是 =(代表赋值)。
"if (temp = 'P')" 行意味着您正在将 'P' 分配给 temp,然后测试 temp 是否不同于 0(空字符),当然它是('P' 不同于 0! ).
正确的测试写法是:
if (temp == 'P')
另外,为什么第一个for循环和第二个for循环的limit不一样?你确定吗?
最后,为什么用x和y来命名整数类型的变量,用i和j来命名不是更好吗?
我正在尝试计算特定字符在二维数组中出现的次数。问题是它正在计算数组中的所有字符。我不知道为什么。
int P = 0;
int p = 0;
int R = 0;
int r = 0;
int N = 0;
int n = 0;
int B = 0;
int b = 0;
int Q = 0;
int q = 0;
for (int x = 0; x < BOARD_SIZE + 1; x++) // This side is 9
{
for (int y = 0; y < BOARD_SIZE; y++) // This side is 8
{
char temp = ' '; // Tried using temp as pass through, but no difference
temp = chessBoards[x][y];
// cout << temp; // When this is on it prints each element of the array list in order with a number beside it
if (temp = 'P') // This is just one character I am trying to count
{
++P; // It increments for every character so it's not checked properly
}
}
}
cout << P << endl << endl; // This is what I am using to test output
将if (temp = 'P')
更改为if (temp == 'P')
这只是一个错字..
if (temp = 'P')
您正在使用赋值运算符而不是比较。
要测试是否相等,请使用 == 而不是 =(代表赋值)。 "if (temp = 'P')" 行意味着您正在将 'P' 分配给 temp,然后测试 temp 是否不同于 0(空字符),当然它是('P' 不同于 0! ). 正确的测试写法是:
if (temp == 'P')
另外,为什么第一个for循环和第二个for循环的limit不一样?你确定吗?
最后,为什么用x和y来命名整数类型的变量,用i和j来命名不是更好吗?