[英]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;
}
}
因此,對於某些上下文,我必須使用二維數組作為存儲單元格的網格來實現康威的生命游戲。 活細胞用 * 字符表示,死細胞用 '.' 表示。 特點。
游戲規則如下:
現在我必須檢查初始網格的副本並計算單元格數量並根據這些規則修改原始網格:
我已經調試了幾個小時,我真的不明白為什么我的代碼會進入死循環?
通常無限循環來自失誤,我很快閱讀了您的代碼並發現了在嵌套循環內,您在嵌套循環中專門在最內層循環中復制了框,您增加了i而不是j :
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.