首页 > 解决方案 > 为什么这段代码用 0 填充数组的第 13 个元素?

问题描述

我刚刚开始学习 C++,如果这个问题低于社区的工资等级,我深表歉意。

我不太明白是什么导致这段代码用 0 填充数组的每个第 13 个元素。

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <iomanip>
//#include "_pause.h"

using namespace std;

//////////////////////////////////////////////////////////////////
//                               NOTE
// This is your program entry point. Your main logic is placed
// inside this function. You may add your functions before this
// "main()", or after this "main()" provided you added reference
// before this "main()" function.
//////////////////////////////////////////////////////////////////

int main()
{
    
    int count = 1;
    int seat[5][7];
    int ctr, ctr2;
    bool cont=true;
    char choice[3];
    do
    {
        for(int ctr=0;ctr<5;ctr++)
        {
            for(int ctr2=0;ctr2<7;ctr2++)
            {
                if(seat[ctr][ctr2]|=0)
                {
                    seat[ctr][ctr2]=count;
                }
                count++;
                cout<<seat[ctr][ctr2]<<"\t";
            }
            cout<<endl;
        }
        cout<<"Do you want to continue (Y/N)?";
        cin>>choice;
        if (choice=="Y" || choice=="YES")
        {
            cont=true;
        } else (cont==false);
    } while (cont=true);

    system("pause");
    return 0;
}

这是第 14 个循环中变量的样子:

可变表

感谢这些提示,如果这是一个非常基本的问题,我们深表歉意。我仍在努力理解这些概念。

标签: c++

解决方案


数组seat[5][7]未初始化。这会导致未定义的行为。在这种情况下,看起来未定义的行为是它被初始化为:

int seat[5][7] = {
  {1,1,1,1,1,1,1},
  {1,1,1,1,1,0,1},
  {1,1,1,1,1,1,1},
  {1,1,1,1,1,1,1},
  {1,1,1,1,1,1,1},
};

以这种方式初始化时,您的代码将可靠地体验您所看到的输出。

https://repl.it/repls/EnchantingUncommonOrders#main.cpp

作为旁白..

if (seat[ctr][ctr2] |= 0) {
  seat[ctr][ctr2] = count;
}

在功能上与

if (seat[ctr][ctr2] != 0) {
  seat[ctr][ctr2] = count;
}

因此,如果座位数组的任何值初始化为零,您的代码将不会更新该插槽。


推荐阅读