只能生成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); } }
运行结果:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器