[英]Why does my program go into an infinite loop?
#include <iostream>
#include <iomanip>
#include <string>
int main(){
int r,c,g;
std::cin>>r>>c>>g;
char box[r][c];
char copy[r][c];
for(int i = 0; i < r; ++i){
for(int j = 0; j < c; ++j){
std::cin >> box[i][j];
}
}
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
copy[i][j] = box[i][j];
}
}
//making a copy of box
for(int i=0;i<g;i++){
int count = 0;
for(int i=0; i<r; i++){
for(int j=0; j<c; j++){
count =0;
if((i-1 >= 0 ) && (j-1>=0)) {
if(copy[i-1][j-1] == '*'){
count+=1;
}
}
if(j-1>=0){
if(copy[i][j-1] == '*'){
count+=1;
}
}
if((i+1 < r ) && (j-1>=0)){
if(copy[i+1][j-1] == '*'){
count+=1;
}
}
if(i+1<r){
if(copy[i+1][j] == '*'){
count+=1;
}
}
if((i+1<r) && (j+1<c)){
if(copy[i+1][j+1] == '*'){
count+=1;
}
}
if(j+1<c){
if(copy[i][j+1] == '*'){
count+=1;
}
}
if ((i-1>=0) && (j+1<c)){
if(copy[i-1][j+1] == '*'){
count+=1;
}
}
if (i-1>=0){
if(copy[i-1][j] == '*'){
count+=1;
}
}
//modify the original grid based on the rules
if ((count<2) || (count>3)){
box[i][j] = '.';
}
if((copy[i][j]=='.') && (count == 3)){
box[i][j] = '*';
}
}
}
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
box[i][j] = copy[i][j];
}
}
}
for(int i=0; i<r; i++){
for(int j=0; j<c; j++){
if (j < c - 1){
std::cout<<box[i][j]<<" ";
}
else{
std::cout<<box[i][j];
}
}
std::cout<<std::endl;
}
}
So for some context, I must implement Conway's Game of Life using a two-dimensional array as a grid in which I store the cells.因此,对于某些上下文,我必须使用二维数组作为存储单元格的网格来实现康威的生命游戏。 Live cells are denoted as * characters, dead cells are denoted by the '.'
活细胞用 * 字符表示,死细胞用 '.' 表示。 character.
特点。
The rules for the game are as followed:游戏规则如下:
Now I must check the copy of the initial grid and count the cells and modify the original based on these rules:现在我必须检查初始网格的副本并计算单元格数量并根据这些规则修改原始网格:
Ive been debugging for hours and I really don't understand why my code goes into an infinite loop?我已经调试了几个小时,我真的不明白为什么我的代码会进入死循环?
Usually infinite loops come from blunders, I read really quickly your code and spotted that inside the nested loop where you copy the box specifically at the most inner loop you increase i instead of j :通常无限循环来自失误,我很快阅读了您的代码并发现了在嵌套循环内,您在嵌套循环中专门在最内层循环中复制了框,您增加了i而不是j :
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.