3

我该怎么做?

这是我这样做的尝试:

srand (time(NULL));
seed = ((double)rand()) / ((double)RAND_MAX) * 10 + 0.5;

还有什么是在 0 和一些 int x 之间创建一个随机整数的方法。[0,x]

4

3 回答 3

11

C++11 方式:

#include <random>

std::random_device rd;
std::default_random_engine generator(rd()); // rd() provides a random seed
std::uniform_real_distribution<double> distribution(0.1,10);

double number = distribution(generator);

如果您只想要整数,请改用此分布:

std::uniform_int_distribution<int> distribution(0, x);

C++11 在这方面确实很强大并且设计得很好。生成器与分布的选择是分开的,范围被考虑在内,线程安全,性能好,人们花了很多时间来确保一切都是正确的。最后一部分比你想象的更难做对。

于 2013-10-29T08:03:30.277 回答
2
srand (time(NULL));
seed = ((double)rand()) / ((double)RAND_MAX) * 9.9 + 0.1;

最多显示 2 位小数:

printf("%.2lf\n", seed);

如果x您需要小于RAND_MAX,则使用

seed = rand() % (x+1);

在 中生成一个整数[0, x]

于 2013-10-29T08:00:22.210 回答
0
#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>
#include <cstdlib>

using namespace std;

float r(int fanwei)
{
    srand( (unsigned)time(NULL) ); 
    int nTmp =  rand()%fanwei;
    return (float) nTmp / 10;
}

int main(int argc, const char * argv[])
{
    cout<<r(100)<<endl; 
    return 0;
}
于 2013-10-29T08:41:30.120 回答