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

如何用指定范围随机数除法结果填充二维数组(结果不在(-2,2))?程序异常求助

程序崩溃返回3221225620的解决办法

问题背景

需要用两个指定范围随机数的除法结果填充11×11二维数组,要求结果不在(-2,2)区间:

  • 第一个随机数范围:(-15,5)
  • 第二个随机数范围:(-2,2)
    但在Dev-C++中运行时,程序仅输出少量内容就崩溃,返回值3221225620。

错误根源

  1. 整数除以零:第二个随机数的生成逻辑会产生0值。原代码中num2 = (rand() % (2 + 2 + 1)) - 2会生成-2、-1、0、1、2这几个值,当num2为0时,执行res = num1 / num2会触发整数除以零的未定义行为,直接导致程序崩溃(3221225620对应Windows平台的STATUS_INTEGER_DIVIDE_BY_ZERO错误)。
  2. 原do-while循环没有提前过滤num2为0的情况,一旦生成0就立刻崩溃,无法进入循环判断阶段。

修复后的代码

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

int main() {
    int array[11][11];
    int num1 = 0;
    int num2 = 0;
    int res = 0;
    srand(time(NULL));  

    for (int i = 0; i < 11; i++) {
        for (int j = 0; j < 11; j++) {
            do {
                // 生成(-15,5)范围内的整数:-15到5(包含两端)
                num1 = (rand() % (5 + 15 + 1)) - 15;
                // 生成(-2,2)范围内的非零整数:-2、-1、1、2
                int temp = rand() % 4;
                switch(temp) {
                    case 0: num2 = -2; break;
                    case 1: num2 = -1; break;
                    case 2: num2 = 1; break;
                    case 3: num2 = 2; break;
                }
                res = num1 / num2;
                printf("%d/%d=%d\t", num1, num2, res);
            // 确保结果不在(-2,2)区间,即res <= -3 或 res >=3
            } while (res > -2 && res < 2);
            
            array[i][j] = res;
            printf("\narray[%d][%d]=%d\n", i, j, array[i][j]);
        }
    }
    return 0;
}

关键修改说明

  • 避免num2为0:通过生成0-3的随机数,再映射为-2、-1、1、2,彻底排除0值,解决除以零的崩溃问题。
  • 修正循环条件:原条件res >= -2 && res <= 2会把边界值-2、2也包含进去,改为res > -2 && res < 2,确保结果不在(-2,2)区间内(整数结果满足<= -3或>=3)。

验证结果

修复后程序可以完整运行,遍历填充整个11×11数组,不会出现崩溃情况,输出内容符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 22:07:28