c++ - 为什么这段代码用 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 个循环中变量的样子:
感谢这些提示,如果这是一个非常基本的问题,我们深表歉意。我仍在努力理解这些概念。
解决方案
数组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;
}
因此,如果座位数组的任何值初始化为零,您的代码将不会更新该插槽。
推荐阅读
- java - Java Socket IO 不发送到 Node.js,但可以连接和接收
- java - 将列表中的元素移动到最后一个索引
- java - 休眠序列化失败
- c++ - 计算二叉搜索树 C++ 中的节点数
- string - AWK 比较两个字符串变量
- reactjs - 创建并发布可重用的 React Native UI 组件库
- python - Python Pandas - 如果使用 groupby 函数对两列中的数据进行汇总,则将一列中的数据除以另一列
- flutter - 用于 OnLongPressed 的颤振 GestureDetector
- webpack - 如何追踪捆绑节点模块的原因
- ios - 如何在 ViewController 中显示弹出窗口