C++中嵌套条件的X模式
我有以下代码C++中嵌套条件的X模式,c++,C++,我有以下代码 #include <iostream> using namespace std; int main(){ int column, row, n(5); int middle = (n+1)/2; for(column = 1; column <= n; column++){ for(row = 1; row <= n; row++){ if((n % 2) == 1){
#include <iostream>
using namespace std;
int main(){
int column, row, n(5);
int middle = (n+1)/2;
for(column = 1; column <= n; column++){
for(row = 1; row <= n; row++){
if((n % 2) == 1){
if(column == middle && row == middle)
cout << "o";
} else if(column == row){
cout << "\\";
} else if(row == (n-column+1)){
cout << "/";
} else{
cout << " "; }
} cout << endl;
}
return 0;
}
但是如果n值是奇数,那么它只打印了一堆没有图案的空格。代码出了什么问题?这是因为您总是点击ifn%2==1块而不打印任何内容 您需要将其更改为ifcolumn==middle&&row==middle&&n%2==1 示例代码:
#include <iostream>
using namespace std;
int main(){
int column, row, n(5);
int middle = (n+1)/2;
for(column = 1; column <= n; column++){
for(row = 1; row <= n; row++){
if(column == middle && row == middle&& (n % 2) == 1)
{
cout << "o";
} else if(column == row){
cout << "\\";
} else if(row == (n-column+1)){
cout << "/";
} else{
cout << " "; }
} cout << endl;
}
return 0;
}
这对我很有用:
int main() {
int n = 5;
for (int row = 0; row < n; row++)
{
for (int col = 0; col < n; col++)
{
if ((col == row) && (col == n - 1 - row))
{
cout << 'o';
}
else if (col == row)
{
cout << '\\';
}
else if (col == n - 1 - row)
{
cout << '/';
}
else
{
cout << ' ';
}
}
cout << endl;
}
return 0;
}
在将问题发布到此处之前,您是否尝试过使用调试器调试代码?有了一个好的调试器,您可以暂停代码的执行,并检查每一行上变量的值如果n%2==1{…}否则{…}对于某些n来说,else部分永远不会命中。@Lucifer1002您可以处理奇数,但需要稍加修改。
\ /
\ /
o
/ \
/ \
int main() {
int n = 5;
for (int row = 0; row < n; row++)
{
for (int col = 0; col < n; col++)
{
if ((col == row) && (col == n - 1 - row))
{
cout << 'o';
}
else if (col == row)
{
cout << '\\';
}
else if (col == n - 1 - row)
{
cout << '/';
}
else
{
cout << ' ';
}
}
cout << endl;
}
return 0;
}