菜鸡咕咕叫

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
统计
 

只能生成1-max之间的随机数,再具体需要更改子函数中的条件。

复制代码
#include<stdio.h>
#include<vector>
#include<stdlib.h>
#include<sys/time.h>

using namespace std;
class CRand
{
public:
  vector<int> m_val;
  CRand();
  ~CRand();
  void Rand(const int minvalue,const int maxvalue,const int totalcount,const bool brep=true);
};

int main()
{
  CRand cr;
  
  int count,max,min;  
  printf("生成m个x-y之间不能重复的整数:(依次输入m x y)\n");
  scanf("%d %d %d",&count,&min,&max);
  cr.Rand(min,max,count,false);
  for(int i=0;i<count;i++)
    printf("m_val[%d]=%d\n",i+1,cr.m_val[i]);

  cr.m_val.clear();

  printf("\n\n生成m个x-y之间能够重复的整数:(依次输入m x y)\n");
  scanf("%d %d %d",&count,&min,&max);
  cr.Rand(min,max,count,true);
  for(int i=0;i<count;i++)
    printf("m_val[%d]=%d\n",i+1,cr.m_val[i]);
}

CRand::CRand()
{
  struct timeval t;

  gettimeofday(&t,NULL);
  
  srand(t.tv_sec+t.tv_usec);  

}

CRand::~CRand()
{
  m_val.clear();
}

void CRand::Rand(const int minvalue,const int maxvalue,const int totalcount,const bool brep)
{
  int data;
  CRand();
  for(int i=0;m_val.size()<totalcount;i++)
  { 
    data=rand()%maxvalue+minvalue;
    if(!brep)
    {
      if(m_val.size()==0) m_val.push_back(data);
      else 
      { 
        int j; 
        for(j=0;j<m_val.size();j++)
          { if(data==m_val[j]) break; }
        if(j==m_val.size()) m_val.push_back(data);
      }
    }
    else m_val.push_back(data);
   // if(i<totalcount) continue;
   // printf("%d ",data);
  }
}
复制代码

运行结果:

 

posted on   菜鸡咕咕叫  阅读(41)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
 
点击右上角即可分享
微信分享提示