在C ++中生成随机长数 [英] generate random long number in C++

查看:139
本文介绍了在C ++中生成随机长数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道要生成随机长数,我们在Java中执行以下步骤

We know that to generate random long number we do following steps in Java

Random r=new Random()
 return r.nextLong();

这些代码在C ++中会是什么样子?像这样?

what will be equivalent of this code in C++? like this?

return (long) rand();


推荐答案

< cstdlib& / code>提供了int rand()。你可能想查看手册页。如果long在您的系统上大于int,您可以调用rand()两次并将第一个值放在高位字中。

<cstdlib> provides int rand(). You might want to check out the man page. If long is bigger than int on your system, you can call rand() twice and put the first value in the high word.

#include <cstdlib>

long lrand()
{
    if (sizeof(int) < sizeof(long))
        return (static_cast<long>(rand()) << (sizeof(int) * 8)) |
               rand();

    return rand();
}

(这不太可能是long不等于或两倍大小int,所以这是实用的,如果不是理论上完美)

(it's very unlikely that long is neither the same as or double the size of int, so this is practical if not theoretically perfect)

但是检查你的文档rand()。这不是一个伟大的发电机,但足够好的大多数事情。你需要调用srand()来初始化随机数生成系统。其他人评论说,Windows不会返回sizeof(int)随机化位,因此您可能需要调整以上。

Check your docs for rand() though. It's not a great generator, but good enough for most things. You'll want to call srand() to initialise the random-number generation system. Others have commented that Windows doesn't return sizeof(int) randomised bits, so you may need to tweak the above.

这篇关于在C ++中生成随机长数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆