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

C语言rand()设置最小值为1仍生成0的问题排查求助

问题根因

  • 你在循环中每生成1个楼层值就对整个数组执行排序,但此时数组中还未完成所有元素的赋值:malloc申请的内存不会自动初始化,未赋值的元素是随机的垃圾值(你遇到的就是垃圾值里刚好有大量0),排序时这些0会被提前到数组前部,替换掉你已经生成的合法楼层值的位置,最终输出就会出现大量0。
  • 同时你排序后直接打印当前循环下标的数组元素,此时该位置的元素早就被排序操作替换成了未初始化的垃圾值,自然不是你刚生成的1~20的随机数。

修复方案

调整循环逻辑:先完成所有楼层值的生成,再统一执行一次排序,最后统一遍历输出即可。

修复后参考代码

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
void sort(int a[], int m){
// 定义排序函数,对数组元素做升序排列
    int i = 0;
    int j = 0;
    int tmp = 0;
    for (i = 0; i < m - 1; i++){
        for (j = 0; j < m -i - 1; j++){
            if (a[j] > a[j+1]){
                tmp = a[j+1];
                a[j+1] = a[j];
                a[j] = tmp;
            }
        }
    }
}
int main(){

    int capacity = 18;
    int stopTime = 15;
    int floors = 20;
    int movePerFloorTime = 3;
    double averageTotalTime = 0;
    double minTotalTime = 0;
    double maxTotalTime = 0;
    double averageTimePerPassenger = 0;

    srand(1);
    int passengers = rand() % (capacity + 1);
    int i = 0;
    printf("%d\n",passengers);
    int *destination;
    // 申请内存后加判空逻辑避免野指针
    destination = (int*)malloc(passengers*sizeof(int));
    if(destination == NULL){
        perror("malloc申请内存失败");
        return 1;
    }
    // 第一步:生成所有楼层值
    for (i = 0; i < passengers; i++){
        destination[i] = rand() % floors + 1;
    }
    // 第二步:统一排序
    sort(destination, passengers);
    // 第三步:统一输出
    for (i = 0; i < passengers; i++){
        printf("%d ", destination[i]);
    }
    printf("\n");
    // 释放malloc申请的内存避免内存泄漏
    free(destination);
    return 0;
}

内容的提问来源于stack exchange,提问作者levi.weiwei

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 20:36:05