You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言生命游戏程序输入百分比后无响应问题求助

康威生命游戏程序卡死问题修复

核心问题

程序选择“生成随机状态”并输入百分比后无响应,根源是死循环:Matrix结构体的data数组未初始化,内存中是随机垃圾值,randomize函数里的判断m->data[row][col] == ' '几乎永远不成立,导致cells无法递减,循环永远无法结束。

修复步骤

1. 初始化随机状态的细胞矩阵

在randomize函数开头,先将所有细胞初始化为空格(死细胞),确保后续随机赋值逻辑能正常执行:

void randomize(Matrix* m, int percent) {
    m->rows = MAX_ROWS;
    m->cols = MAX_COLS;
    // 初始化所有细胞为死状态(空格)
    for (int i = 0; i < m->rows; i++) {
        for (int j = 0; j < m->cols; j++) {
            m->data[i][j] = ' ';
        }
    }
    int cells = (m->rows * m->cols) * (percent / 100.0f);
    srand(time(NULL));
    while (cells > 0) {
        int row = rand() % m->rows;
        int col = rand() % m->cols;
        if (m->data[row][col] == ' ') {
            m->data[row][col] = '*';
            cells--;
        }
    }
}

2. 修复其他编译/逻辑错误

  • 删除load_from_file函数中多余的#符号(会导致编译失败):
// 原错误代码片段
if (ch == '\n') {
    row_idx++;
    continue;
}
#   // 移除该行
    m->data[row_idx][m->cols] = ch;
m->cols++;
  • 修正check_cell函数的逻辑错误,避免错误复活/保留细胞:
void check_cell(Matrix* m, int row, int col) {
    char neighbors_count = neighbor_count(m, row, col);
    char current_cell = m->data[row][col];

    if (current_cell == '*') {
        // 存活细胞:邻居数<2或>3时死亡
        if (neighbors_count < 2 || neighbors_count > 3) {
            m->data[row][col] = ' ';
        }
        // 邻居数2/3时保持存活,无需操作
    } else {
        // 死亡细胞:邻居数=3时复活
        if (neighbors_count == 3) {
            m->data[row][col] = '*';
        }
    }
}

原问题操作步骤

  1. 从文件加载
  2. 生成随机状态
    输入选项2
    输入初始存活细胞百分比:10

原操作截图

操作截图

内容的提问来源于stack exchange,提问作者HerrYetii

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 20:02:22