如何在C中生成随机整数? [英] How to generate a random int in C?

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

问题描述

在C中是否有生成随机int数的函数?还是我必须使用第三方库?

Is there a function to generate a random int number in C? Or will I have to use a third party library?

推荐答案

注意:请勿使用rand()进行安全保护.如果您需要一个密码安全的号码,请查看此答案.

Note: Don't use rand() for security. If you need a cryptographically secure number, see this answer instead.

#include <time.h>
#include <stdlib.h>

srand(time(NULL));   // Initialization, should only be called once.
int r = rand();      // Returns a pseudo-random integer between 0 and RAND_MAX.

编辑:在Linux上,您可能更喜欢使用随机和随机.

Edit: On Linux, you might prefer to use random and srandom.

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

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