变量更改事件的值,当不对它们进行操作时
value of variable change event when don't do operation on them
我有此代码:
#include <iostream>
#include<cstdio>
#include<conio.h>
#include<windows.h>
#define BOARDSIZE 3
using namespace std;
int board[BOARDSIZE][BOARDSIZE];
int cnt = 0;
int minCount = BOARDSIZE*BOARDSIZE;
void boardSwitch(int x, int y){
for(int i = x-1; i <= x+1; i++){
for(int j = y-1; j <= y+1; j++){
if((i>=0) && (j>=0)){
board[i][j] = board[i][j] ^ 1;
}
}
}
}
bool isOn(){
int i, j;
for(i = 0; i < BOARDSIZE; i++){
for(j = 0; j < BOARDSIZE; j++){
if(!board[i][j]){
return 0;
}
}
}
return 1;
}
void boardDisp(){
for(int i = 0; i <BOARDSIZE; i++){
for(int j = 0; j < BOARDSIZE; j++){
cout<<board[i][j]<<" ";
}
cout<<endl;
}
}
void turn(int x){
int i, j;
j = x%BOARDSIZE;
i = (x-j)/BOARDSIZE;
if(x == 0){
cnt = 0;
}
for(int k = 0; k <=1; k++){
printf("%d n", cnt);
cout<<i<<" "<<j<<" cnt = "<<cnt<<endl;
//getch();
if(k == 1){
boardSwitch(i, j); //switch on (i,j) position
//cout<<i<<" "<<j<<" cnt = "<<cnt<<endl;
//cnt++;
//cout<<"switch on "<<i<<" "<<j<<" cnt = " <<cnt<<endl;
}
if(x == BOARDSIZE*BOARDSIZE-1){
// if(isOn()){
// minCount = minCount < cnt ? minCount : cnt;
// }
}
else{
turn(x+1);
}
}
boardSwitch(i, j); // return status before switch
//cnt--;
}
int main(){
for(int i = 0; i < BOARDSIZE; i++){
for(int j = 0; j < BOARDSIZE; j++){
board[i][j] = rand()%2; }
}
boardDisp();
turn(0);
if(minCount == BOARDSIZE*BOARDSIZE){
//There is no way to turn board on
cout<<"There is no way to turn board on";
}else{
cout<<minCount;
}
return 0;
}
在我的思想中,cnt是全局变量,每个函数都可以更改其值。但是没有函数更改其值,但是当我运行该代码时(通过代码块,Visual C )有时会打印出CNT变量和SOMTINE 0的值1。这是为什么 ?
带有代码时,turn()一直以x值越来越多地调用(8)。
。那时,我设置为" 2",J设置为'2'。然后,您致电Boardswitch(2,2)。
您的问题发生在BoardSwitch()中。您的for()循环一直保持运行,直到i和j都等于3,最终导致写入板[3] [3]。此位置不存在,因此您只是在变量的末尾写下 - 那时,任何事情都可能会被忽略。在您的情况下,CNT被覆盖了。
要点是,没有任何东西可以阻止您在C/C 中写下数组的末尾。您只需开始写入记忆,而不是您认为的,并且该程序开始行为不可预测。
最终您需要修复逻辑。同时,您可能会尝试的一件事是创建一个函数来包装到数组并为您执行界限检查。例如:
void writeToBoard(int i, int j, int value) {
if (i >= BOARDSIZE) {
printf("ERROR: Attempted to write outside array.n");
return;
} else if(j >= BOARDSIZE) {
printf("ERROR: Attempted to write outside array.n");
return;
} else {
board[i][j] = value;
}
}
然后用调用此函数的呼叫将所有写入数组替换为数组。
当问题以更易于调试方式发生时,这将发现问题。
将木板包裹在对象中,使该对象私有,并将这种事物视为成员函数是封装的一个很好的例子。
一个更好的解决方案是使用标准的库容器(有效)为您提供此操作。这并不总是一种选择,很高兴从概念上知道这种事情是如何工作的。但是,通常,很少有理由实现自己的界限。这就是为什么我们拥有标准库。
相关文章:
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 重载操作程序时出错>>用于类中的字符串 memebr
- Android NDK传感器向事件队列报告奇怪的间隔
- 从文本文件中读取时钟时间和事件时间并进行处理
- 对字符串进行位操作
- WMI检测进程创建事件-c++
- EvtExportLogneneneba API正在将远程计算机的事件日志保存到远程PC本身.如何将其保存到主机
- 我可以在 C++ 中的函数体之外进行操作吗?
- MPI突然停止了对多个核心的操作
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 对字符数组中的元素执行逐位操作
- 如何在directx/c++中进行平移/缩放操作
- 墨迹画布操作事件
- Boost状态机语言-"操作"中的"发布"事件
- 狂想曲C++状态图 - 事件(似乎有效)与触发操作(似乎什么都不做)
- 变量更改事件的值,当不对它们进行操作时
- 将事件/操作连接到 QPlainTextEdit
- 为什么boost::互斥使用原子操作和事件,而不是关键部分
- 如何在其他类的嵌套循环中获得主事件循环QCoreApplication,以实现网络操作
- 用c++ (ATL, MFC或纯c++)处理COM事件,实现Java互操作