如何打印N X N框的对角线?检查我的代码


int main()
{
int n, i, j;
cin >> n;
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
if (i == 0 || i + j == n - 1)
{
cout << "*";
}
else
cout << " ";
}
cout << "n";
}
return 0;
}

预期的输出是这样的(如果我输入no 5,它应该打印5x5的对角线(

*     *
*  *
*
*  *
*      *

绘制模式不需要2个for循环。一个循环就可以了。

只要记下这两颗星的位置就行了。

类似:

#include <stdio.h>
int main(void) {
int n = 6;
int starApos = 0;
int starBpos = n - 1;
for (int i=0; i < n; ++i)
{
if (starApos < starBpos)
{
printf("%*s", starApos, "");                // spaces before A
printf("*");                                // A
printf("%*s", starBpos - starApos - 1, ""); // spaces between A and B
printf("*");                                // B
}
else if (starApos == starBpos)
{
printf("%*s", starApos, "");                // special case: only 1 *
printf("*");
}
else
{
printf("%*s", starBpos, "");
printf("*");
printf("%*s", starApos - starBpos -1, "");
printf("*");
}
printf("n");
++starApos;    // Move positions
--starBpos;
}
return 0;
}

输出n=6:

*    *
*  *
**
**
*  *
*    *

输出n=5:

*   *
* *
*
* *
*   *

要使第一个对角线正确,请放i + j == n + 1而不是i + j == n - 1。最后,加上|| j == i使另一条对角线。

我还建议您删除i == 0(i从1开始,只上升,所以它永远不会是0(,在代码中添加一个更好的索引,如果您真的不需要,用#include <iostream>替换#include <bits/stdc++.h>

你的程序应该是这样的:

#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= n; j++)
{
if (i + j == n + 1 || j == i)
cout << "*";
else
cout << " ";
}
cout << "n";
}
return 0;
}

对于一个完全使用C的程序,下面的代码可以工作。确保在X中的每个*处查找行和列"索引"之间的关系(即,假设您正在形成的X是一个2D数组(。

#include <stdio.h>
int main(void) {
int size = 0;
// Ask user to enter size of x, then scan input 
printf ("Enter size: ");
scanf("%d", &size);

// Only an odd input can be accepted 
if (size > 0 && size % 2 != 0) {
for (int row = 0; row < size; row++) {

for (int col = 0; col < size; col++) {

if (row == col) {
//Print one diagonal 
printf("*");
} else if (row + col == size - 1) {
//Print the other diagonal 
printf("*");
} else {
//Print empty spaces 
printf(" ");
}
} 

//Move to next row 
printf ("n");
}
}
return 0;
}

最新更新