srand((无符号)(时间(NULL))); (rand())/(RAND_MAX/2) - 1 个 C# 等效项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/367947/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 00:46:10  来源:igfitidea点击:

srand((unsigned)(time(NULL))); (rand())/(RAND_MAX/2) - 1 C# equivalent

c#equivalentsrand

提问by

What is the c# equivalent of the following c++:

以下 c++ 的 c# 等效项是什么:

srand((unsigned)(time(NULL)));
weight=(double)(rand())/(RAND_MAX/2) - 1;

回答by Frans Bouma

To do random value generation in .NET, you should use the Random class. to seed it with a time value, use: Random rand = new Random((int)DateTime.Now.Ticks);

要在 .NET 中生成随机值,您应该使用 Random 类。用时间值播种它,使用: Random rand = new Random((int)DateTime.Now.Ticks);

For further specifics, it's best to check out the docs about the Random class in the MSDN, e.g. which methods are available.

有关更多细节,最好查看 MSDN 中有关 Random 类的文档,例如哪些方法可用。

回答by schnaader

Random rnd = new Random((int)DateTime.Now.Ticks);
return rnd.Next(-1,1);

回答by ICR

The paramaterless constructor for Random uses "a time-dependent default seed value" so all you need is:

Random 的无参数构造函数使用“依赖于时间的默认种子值”,因此您只需要:

Random rnd = new Random();
return rnd.Next(-1, 1);