【问题标题】:I cant understand why this loop freezes我不明白为什么这个循环会冻结
【发布时间】:2016-01-24 02:16:39
【问题描述】:

有人可以向我解释一下这段代码有什么问题吗?我的董事会不应该被填满吗? (我上面有两个函数,一个生成随机数,另一个打印数组)

功能:

void map(char a[3][3]){

    int row, column;

    for(row=0;row<3;row++){

        for(column=0;column<3;column++){

            printf ("%c       ", a[row][column]);

        }
        printf("\n \n \n \n \n");
}
}
float getRand() {

    return ((rand() / (RAND_MAX+1.0))*9)+1;
}

主要:

srand( time(NULL) );
    int r,c,ui,cntr,cntr2,ran,g,x;
    char kb, aray[3][3]={{'.','.','.'},{'.','.','.'},{'.','.','.'}};
    getRand();
    ran=getRand();

for(cntr2=0;cntr2<5;cntr2++){
                g=ran/3;
                x=ran%3;
                if(aray[g][x]=='.'){
                    aray[g][x]='O';
                    system("cls");
                    map(aray);
                }
                else{
                    cntr2--;
                }

        }

【问题讨论】:

  • 它做错了什么?它应该做什么而不是?
  • 能否提供map()和getRand()函数的代码?
  • 现在在 ^^^^^ 上使用调试器

标签: c arrays loops if-statement multidimensional-array


【解决方案1】:

假设getRand返回一个介于0和9之间的数字,一旦循环迭代一次,array[g][x]中就有一个O

在下一次迭代中,ran 没有改变,因此gx 与之前的值相同。现在,array[g][x] 包含一个 O,因此执行 else 语句,并撤消 cntr2++,这将保持在值 1,从而导致无限循环。

【讨论】:

  • 是的,但不应该只在找到一个已经存在的值的情况下?
  • 稍微扩展了解释-希望更有意义?
  • 非常感谢您的精彩解释!
猜你喜欢
  • 1970-01-01
  • 2021-08-31
  • 2017-04-26
  • 1970-01-01
  • 2015-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多