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

C++使用rand生成随机数存入数组统计元素次数结果恒为0如何修复

问题原因&修复方案

核心错误点

  • 重复创建Rand类对象:main函数中先后创建了call和call2两个独立的Rand实例,call实例调用Random_function后保存的range、min、max参数仅属于call本身,新创建的call2的成员变量都是未初始化的垃圾值,直接调用Count_function逻辑完全错误。
  • 随机数未持久化存储:Random_function中生成的随机数仅打印到控制台,没有存储到类的成员中,统计阶段根本无法获取之前生成的数值列表。
  • 计数逻辑完全错误:原Count_function中只生成1次随机数就给整个数组赋值,相当于统计的是新生成的单个随机数和目标值是否相等,和之前生成的随机数没有任何关系。
  • 非标准语法使用:int array[range]属于C语言可变长数组扩展,不属于C++标准语法,兼容性差。

修复步骤

  1. 给Rand类添加vector<int>类型的成员变量,用于存储生成的随机数
  2. main函数中仅使用1个Rand实例,生成随机数和统计都基于同一个实例
  3. 随机数生成阶段每生成一个数就存入成员vector中
  4. 计数阶段直接遍历已存储的vector统计目标值出现次数
  5. 删除不必要的可变长数组使用

1. 修改后random_function.hpp代码

#pragma once
#include <vector>
using namespace std;
class Rand
{
public:
    Rand();
    int range,min,max;
    vector<int> nums; // 新增存储随机数的成员
    void Random_function();
    void Count_function();
};

2. 修改后random_function.cpp代码

#include <iostream>
#include <ctime>
#include <cstdlib>
#include "random_function.hpp"

using namespace std;

Rand::Rand()
{
    // 初始化成员变量避免垃圾值
    range = 0;
    min = 0;
    max = 0;
}

void Rand::Random_function()
{
    nums.clear(); // 每次生成前清空旧数据
    cout << "Enter amount of numbers to generate: ";
    cin >> range;
    if (range<=0)
    {
        cout <<"Error! Please enter the valid number and try again! "<<endl;
        return;
    }
    cout << "Enter minimum boundary: ";
    cin >> min;
    cout << "Enter maximum boundary: ";
    cin >> max;
    cout << "\n";
    
    if(max<=min || cin.fail())
    {
        cout << "\nError! Please enter the valid value and try again! " << endl;
        return;
    }
    // srand全局只调用一次即可
    static bool seed_init = false;
    if(!seed_init) {
        srand((unsigned)time(NULL));
        seed_init = true;
    }
    
    for(int n=1 ; n <= range; n++)
    {
        int num = min + (rand() % static_cast<int>(max - min + 1));
        cout << num <<endl;
        nums.push_back(num); // 存入数组
    }
    cout <<"\n"<< "Total random numbers generated: " << range<< endl;
}

void Rand::Count_function()
{
    extern int y;
    int count=0;
    // 直接遍历已存储的随机数统计
    for (int num : nums)
    {
        if(num == y)
            count++;
    }
    cout <<"The number of '"<<y<<"'s in the given list is: "<< count <<endl;
}

3. 修改后main.cpp代码

#include <iostream>
#include "random_function.hpp"
using namespace std;
int y;
int main()
{
    Rand call;
    call.Random_function();
    cout<<"Enter the value to count for: ";
    cin>>y;
    // 直接用同一个实例调用计数方法,不要新建call2
    call.Count_function();
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 11:00:00