C++ 随机数和负数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3830663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Random and negative numbers
提问by Max Frai
I have to generate numbers in range [-100; +2000]in c++. How can I do this with rand if there is only positive numbers available? Are there any fast ways?
我必须生成范围[-100; +2000]在 C++ 中。如果只有正数可用,我如何用 rand 来做到这一点?有什么快速的方法吗?
回答by Kendrick
generate a random number between 0 and 2100 then subtract 100.
生成 0 到 2100 之间的随机数,然后减去 100。
A quick google search turned up a decent looking article on using Rand().It includes code examples for working with a specific range at the end of the article.
快速的谷歌搜索找到了一篇关于使用 Rand()的不错的文章。它包括在文章末尾处理特定范围的代码示例。
回答by Jez
Generate a random number between 0 and 2100, and subtract 100.
生成 0 到 2100 之间的随机数,然后减去 100。
回答by Blastfurnace
You can use the C++ TR1 random functions to generate numbers in the desired distribution.
您可以使用 C++ TR1 随机函数生成所需分布的数字。
std::random_device rseed;
std::mt19937 rng(rseed());
std::uniform_int_distribution<int> dist(-100,2100);
std::cout << dist(rng) << '\n';
回答by n8wrl
Can you generate a number from 0-2100 and subtract 100?
你能从 0-2100 中生成一个数字并减去 100 吗?
回答by John Dibling
Here is the code.
这是代码。
#include <cstdlib>
#include <ctime>
int main()
{
srand((unsigned)time(0));
int min = 999, max = -1;
for( size_t i = 0; i < 100000; ++i )
{
int val = (rand()%2101)-100;
if( val < min ) min = val;
if( val > max ) max = val;
}
}
回答by Oliver
Currently my C++ syntax is a little rusty, but you should write a function that takes two parameters: size
and offset
.
目前我的 C++ 语法有点生疏,但您应该编写一个带有两个参数的函数:size
和offset
。
So you generate numbers with the given size
as maximum value and afterwards add the (negative) offset to it.
因此,您以给定的size
最大值生成数字,然后向其添加(负)偏移量。
The function would look like:
该函数将如下所示:
int GetRandom(int size, int offset = 0);
and would be called in your case with:
并且会在您的情况下被调用:
int myValue = GetRandom(2100, -100);
回答by David
In C++0x they will enhance this to provide better support for it with a standard library.
在 C++0x 中,他们将增强这一点,以通过标准库为其提供更好的支持。