在C/C++中以不同的行打印2D矩阵,且不带大括号?

以下是打印2D矩阵的一般方法,以便每一行都以单独的行打印。

null

for ( int i = 0; i < m; i++)
{
for ( int j = 0; j < n; j++)
{
cout << arr[i][j] << " " ;
}
// Newline for new row
cout << endl;
}


如何在不使用任何花括号的情况下打印for循环?

我们强烈建议您尽量减少浏览器,并先自己尝试。

我们可以简单地删除内部卷曲括号,因为有一条线的内部循环。如何去除外曲括号?下面是解决方案。

// C++ program to print a matrix line by line without
// using curly braces.
#include<iostream>
using namespace std;
int main()
{
int m = 2, n = 3;
int mat[][3] = { {1, 2, 3},
{4, 5, 6},
};
for ( int i = 0; i < m; i++)
for ( int j = 0; j < n; j++)
// Prints ' ' if j != n-1 else prints ''
cout << mat[i][j] << " " [j == n-1];
return 0;
}


输出:

1 2 3
4 5 6

真正的诀窍在下面的陈述中 ““[j==n-1] ,解释如下:

” “是一个2个字符的字符串,其中1 字符是空格和2 字符是换行符,所以除了最后一个需要换行符的值之外,每个值后面都需要空格。在C语言中,字符串文字被处理为字符数组[参见 了解更多详细信息]。

对于内部元素,j==n-1语句的计算结果为0(因为对于它们,j

© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享