C++ 如何用0和1填充二维数组。?
如何用0和1填充二维数组。例如,第一行应该用全部1填充。在第二行中,每个第二个元素应填充1,其他元素应填充0。在第三行中,每个第三个元素都应该用1填充,其他元素用0填充。通常有很多方法来完成任务。例如,您可以使用以下解决方案C++ 如何用0和1填充二维数组。?,c++,arrays,for-loop,multidimensional-array,C++,Arrays,For Loop,Multidimensional Array,如何用0和1填充二维数组。例如,第一行应该用全部1填充。在第二行中,每个第二个元素应填充1,其他元素应填充0。在第三行中,每个第三个元素都应该用1填充,其他元素用0填充。通常有很多方法来完成任务。例如,您可以使用以下解决方案 #include <iostream> int main() { const size_t M = 5; const size_t N = 10; int a[M][N]; for ( size_t i = 0; i <
#include <iostream>
int main()
{
const size_t M = 5;
const size_t N = 10;
int a[M][N];
for ( size_t i = 0; i < M; i++ )
{
for ( size_t j = 0; j < N; j++ ) a[i][j] = ( j + 1 ) % ( i + 1 ) == 0;
}
for ( const auto &row : a )
{
for ( int x : row ) std::cout << x << ' ';
std::cout << std::endl;
}
return 0;
}
如果编译器不支持基于范围的for循环
for ( const auto &row : a )
{
for ( int x : row ) std::cout << x << ' ';
std::cout << std::endl;
}
for(常量自动&行:a)
{
for(intx:row)std::cout Try某事(需要一些循环)。如果您遇到了问题,请回来寻求帮助。我已经遇到了问题…因此,首先,您甚至不知道如何编写循环?谢谢…这正是我想要的:)@ynnenu我展示了一个有效的C++代码。谢谢您的帮助:)我得到了它…再次感谢:)我如何计算每列的总和并计算它们?
for ( const auto &row : a )
{
for ( int x : row ) std::cout << x << ' ';
std::cout << std::endl;
}
for ( size_t i = 0; i < M; i++ )
{
for ( size_t j = 0; j < N; j++ ) std::cout << a[i][j] << ' ';
std::cout << std::endl;
}