尝试打印数组不会打印任何内容

Attempt to print an array prints nothing

本文关键字:打印 任何内 数组      更新时间:2023-10-16

我正在尝试创建一个打印数组的程序。我希望这个程序的输出是:

10000
00000
00000
00000
00000

事实并非如此。相反,它只是什么都不打印。没有编译错误。我有Microsoft Visual Studio 2010。

#include "stdafx.h"
#include <iostream>
int main()
{
    using namespace std;
    int a [5] [5] = {0};
    a [1] [1] = 1;
    int xcount = 0;
    int ycount = 0;
    while(xcount < 6);
    {
        cout << a [xcount] [ycount];
        xcount = xcount + 1;
        if(xcount = 6)
        {
            ycount = ycount + 1;
            xcount = xcount + 1;
            if(ycount = 6)
            {
                exit(0);
            }
        }
    }
    return 0;
}

如有任何帮助,我们将不胜感激。

如果我理解正确,您将尝试按列输出数组。您的代码包含许多错误,包括while语句末尾的分号。正确的程序可能看起来像

#include "stdafx.h"
#include <iostream>
int main()
{
    const size_t N = 5; 
    int a[N][N] = { 1 };
    int xcount = 0;
    int ycount = 0;
    while ( true )
    {
        std::cout << a[xcount][ycount];
        if ( ++xcount == N )
        {
            std::cout << std::endl;
            xcount = 0;
            if ( ++ycount == N )
            {
                break;
            }
        }
    }
    return 0;
}
if (xcount=6)  // This sets xcount to 6

将其更改为:

if (xcount==6) // this compares xcount with 6

现在编辑;又回到了问题中:

由于没有任何更改xcount-删除;

,因此while(xcount < 6);将无限循环

删除分号:

while (xcount<6);

除此之外,算法是错误的。更换第二个

xcount=xcount+1;

通过

xcount=0;

循环的附言在这里会更好。它会更干净,因为你知道循环的范围:

for (int ycount=0; ycount<6; ++ycount)
{
    for (int xcount=0; xcount<6; ++xcount)
        cout << a[xcount][ycount];
    cout << endl;
}

请注意,在原始解决方案中并没有换行符。

p.p.S.在比较中使用==。

您应该使用for循环,而不是while试试这个:

for(int xcount=0; xcount<5; xcount++) 
{
      for(int ycount=0; ycount<5; ycount++)
      {
              cout<< a[xcount][ycount];
       }
      cout<<endl;
 }
 a[0][0] = 1;