尝试打印阵列什么都不打印

时间:2013-12-08 22:06:56

标签: c++ arrays loops

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

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;
}

任何帮助都将不胜感激。

4 个答案:

答案 0 :(得分:2)

如果我已正确理解您正在尝试按列输出数组。您的代码包含许多错误,包括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;
}

答案 1 :(得分:1)

if (xcount=6)  // This sets xcount to 6

将其更改为:

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

现在编辑;回到了问题:

while(xcount < 6);无限循环,因为没有任何改变xcount - 删除;

答案 2 :(得分:0)

删除分号:

while (xcount<6);

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

xcount=xcount+1;

通过

xcount=0;

P.S。 for循环在这里会更好。因为你知道循环的范围会更清晰:

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

请注意原始解决方案中没有行分隔符。

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

答案 3 :(得分:0)

您应该使用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;
相关问题