Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

c - 如何在C中生成随机int?(How to generate a random int in C?)

Is there a function to generate a random int number in C? (是否有在C中生成随机int数的函数?) Or will I have to use a third party library? (或者我必须使用第三方库吗?)

  ask by Kredns translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Note : Don't use rand() for security. (注意 :不要使用rand()来保证安全性。) 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.

Edit : On Linux, you might prefer to use random and srandom . (编辑 :在Linux上,您可能更喜欢使用random和srandom 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...