注册 登录
编程论坛 C++教室

请教如何生成一组随机数

heyyroup 发布于 2007-12-16 19:07, 2037 次点击
我在做排序的算法的时候,需要一组数据作为测试数据。
但是一个个输入太麻烦了。
应该怎样才能让系统自动生成一组随机的数呢,比如我需要1个包含100个整数的数组。代码该怎么写。
我翻了一下书。好像是要用srand()函数,但是我不会用啊
哪位能给我一个例子?
8 回复
#2
aipb20072007-12-16 19:29
int a[100];
srand((unsigned) time(0));
for (int i = 0;i < 100;++i)
      a[i] = rand();
#3
liujianlin2007-12-16 20:28
用C++程序,怎么样实现1-33之间的随机数???
#4
无缘今生2007-12-16 20:52
// This program seeds the random-number generator
// with the time, then displays 10 random integers.
//

#include <iostream>
//#include <cstdlib>
//#include <cstdio>
#include <ctime>

using namespace std;

int Random(int MIN, int MAX);   // generate a random number

int main()
{
    // set the random-number seed with the current time
    srand((unsigned)time(NULL));

    cout << "请输入要产生的随机数的个数:";
    int NUM;
    cin >> NUM;

    cout << "现在开始产生随机数..." << endl;
    int min, max;

    cout << "请输入要产生的随机数的下限:";
    cin >> min;
    cout << "请输入要产生的随机数的上限:";
    cin >> max;

    //generate the random numbers
    int randoms;

    for (int i=0; i<NUM; i++)
    {
        randoms = Random(min,max);
        cout << randoms << "  ";
    }
    cout << endl;
    system("pause");
    return 0;
}

int Random(int MIN, int MAX)
{
    return (((double)rand() / (double)RAND_MAX)*MAX + MIN);
}
我前不久也遇到了同样的问题.
我用的就是上面的代码.不知道合不合你的要求.
#5
heyyroup2007-12-16 21:20
感谢感谢
#6
aipb20072007-12-16 21:43
回复 3# 的帖子
rand()%(33-1+1)+1
#7
中学者2007-12-16 21:46
LS,33-1+1=33,怎么还要这样写~
#8
aipb20072007-12-16 22:27
回复 7# 的帖子
要是5到33就是33-5+1=29

呵呵.
#9
中学者2007-12-16 23:05
1