这个python代码的c++版本是什么?我想要一个特殊的随机数,根据一个循环中的特殊数。python版本:
import random
nextRTSeed = 0;
while(True):
nextRTSeed+=1
random.seed(nextRTSeed)
print( "rand ------->> ", (random.random()) )
if(nextRTSeed>10):
break发布于 2021-12-28 01:44:05
直接翻译可能如下所示:
#include <iomanip>
#include <iostream>
#include <random>
int main() {
std::cout << std::fixed << std::setprecision(17); // we want many decimals
std::mt19937 random; // A PRNG
std::uniform_real_distribution<double> dist(0., 1.); // distribution [0,1)
for(int nextRTSeed = 1; nextRTSeed <= 11; ++nextRTSeed) {
random.seed(nextRTSeed); // reseeding the PRNG
std::cout << dist(random) << '\n'; // print random number
}
}注意:很少需要重新播种PRNG (伪随机数生成器)。你通常应该只播一次,然后再继续叫它。如下所示:
int main() {
std::cout << std::fixed << std::setprecision(17);
std::mt19937 prng(std::random_device{}()); // A seeded PRNG
std::uniform_real_distribution<double> dist(0., 1.);
for(int i = 0; i < 11; ++i) {
std::cout << dist(prng) << '\n';
}
}发布于 2021-12-28 01:44:18
下面是如何在C++中得到一个随机数
#include <iostream> // For input/output
#include <cstdlib> // for rand() and srand()
int main()
{
int maxRandValue = 100
srand(time(null)); // Sets seed of random to time now.
std::cout << "The random number is: "<< rand() % maxRandValue; // Range: 0 - 100
}注意,Python/C++中的rand()函数不是随机函数,而是伪随机函数,有关更多信息,请参见以下视频:https://youtu.be/Nm8NF9i9vsQ
再见!
https://stackoverflow.com/questions/70501953
复制相似问题