再次求教!

dxb_828 2005-11-05 11:48:00
怎样输出1-30内各不相同的7个随机数,最好用数组指针做。
...全文
100 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
fiftymetre 2005-11-06
  • 打赏
  • 举报
回复
写错了,改一下 :)
#include <iostream>
#include <math.h>
using namespace std;
void main()
{
int a[7] = {0};
int i, j;
int tmp;
srand(time(0));
for (i = 0; i < 7; i++)
{
bool ishavesame = true;
while (ishavesame)
{
tmp = rand()%31;
ishavesame = false;
for (j = 0; j < i; j++)
{
if (tmp == a[j]) ishavesame = true;
}
if(tmp && !ishavesame)
{
a[i] = tmp;
ishavesame = false;
}
}
}

for (i = 0; i < 7; i++)
{
cout<<a[i]<<endl;
}
}
fiftymetre 2005-11-06
  • 打赏
  • 举报
回复
那生成的时候要判断是否有重复的

#include <iostream>
using namespace std;
void main()
{
int a[7] = {0};
int i, j;
int tmp;
srand(time(0));
for (i = 0; i < 7; i++)
{
bool ishavesame = true;
while (ishavesame)
{
tmp = rand()%31;

for (j = 0; j < i; j++)
{
if (tmp == a[j]) ishavesame = false;
}
if(tmp && ishavesame)
{
a[i] = tmp;
ishavesame = false;
}
}
}

for (i = 0; i < 7; i++)
{
cout<<a[i]<<endl;
}
}

sankt 2005-11-06
  • 打赏
  • 举报
回复
#include<iomanip.h>
#include<time.h>
#include<stdlib.h>

int main()
{


int i,n;
srand(time(NULL));
cout<<"Please input the size of the array."<<endl;
cin>>n;

int *a=new int[n];


for(i=0;i<n;++i)
{
a[i]=rand()%30+1;
cout<<setw(5)<<a[i];

}
cout<<endl;
delete []a;



return 0;
}
megaboy 2005-11-06
  • 打赏
  • 举报
回复
上面的程序都太复杂了,下面这样做就行了:

int a[30];
srand((unsigned)time(NULL));
for(i=0; i<=29; ++i) a[i]=i;
for(i=29; i>=1; ++i) swap(a[i], a[rand()%i]);

a数组里面任意七个元素都是各不相同的随机数。
dxb_828 2005-11-06
  • 打赏
  • 举报
回复
谢谢各位大侠了
wklucky 2005-11-06
  • 打赏
  • 举报
回复
从今开始努力学习C++,太菜了
snowbirdfly 2005-11-06
  • 打赏
  • 举报
回复
恩~~
支持楼上几位~~
都可以实现楼主要求~~~
顶先~~~

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧