C++ 如果不是多个,则使用if语句
我想创建一个5x5数组,在中间有一个hashtag,而不是,但是只有当用户在我在这里标记的区域上输入'a'或'b'时,它才起作用,除非它只有'a'/只有'b',那么我该怎么办?提前谢谢你C++ 如果不是多个,则使用if语句,c++,arrays,if-statement,C++,Arrays,If Statement,我想创建一个5x5数组,在中间有一个hashtag,而不是,但是只有当用户在我在这里标记的区域上输入'a'或'b'时,它才起作用,除非它只有'a'/只有'b',那么我该怎么办?提前谢谢你 #include <iostream> using namespace std; int main() { while (true){ ///Variables: char array[4][4]; //Playing field 5x5 char direc; //Direction
#include <iostream>
using namespace std;
int main()
{
while (true){
///Variables:
char array[4][4]; //Playing field 5x5
char direc; //Direction player moves
for (int x = 0; x <=4; x++){
for (int y = 0; y <= 4; y++){
array[x][y] = '_';
if (direc != 'a' || 'b'){ ///RIGHT HERE!
array[2][2] = '#';
}
cout << array[x][y]; //Starts printing Board
if (y == 4){
cout << endl; //Cuts to next line on print if 4 in a column row
}
}
}
cin >> direc;
cin.get();
}
}
未检查语句或程序其他部分所需的逻辑,但标记的语句应按
(direc != 'a' || direct != 'b')
你的陈述直接a“| |”b”的计算结果始终为true,因为作为逻辑或运算符的第二个操作数的“b”是一个整数值>0,在某些编码中表示字符b,因此被视为true。正如Neil在评论中提到的,ur 5x5字段实际上是4x4,因此u只能访问数组[0][0]到数组[3][3],而你的X和Y在某个点上是4。您应该改为使用此选项:
char array[5][5]
这样您就可以访问索引为4的阵列,希望对您有所帮助
#include <iostream>
using namespace std;
int main()
{
///Variables:
char array[5][5]; //Playing field 5x5
char direc; //Direction player moves
char player;
while (true) {
//get direc
cin >> direc;
cout << direc << "\n";
if (direc == 'a' || direc == 'b') { ///RIGHT HERE!
player = '_';
}
else {
player = '#';
}
for (int x = 0; x <= 4; x++) {
for (int y = 0; y <= 4; y++) {
array[x][y] = '_';
if (x == 2 && y == 2) {
array[x][y] = player;
}
cout << array[x][y]; //Starts printing Board
if (y == 4) {
cout << endl; //Cuts to next line on print if 4 in a column row
}
}
}
}
}
数组的边界为0到3。显示的代码存在太多问题。首先,你的电脑总是从头到尾运行。在请求输入之前检查direc是行不通的。数组超出范围。破布尔逻辑。从第一眼看,只有三个明显的问题。direc!='a'| |'b'相当于direc!='a'| |'b',这是重言式的,因为'b'是一个非零整数,被认为是真的