在C语言的srand函数中,我需要在time(null)之前加上'(unsigned int)'吗?

5
我看过一些关于使用C语言生成随机数的指南: 其中有两件事让我思考:
  1. it is said that in addition to stdlib.h and time.h libraries I have to include the math.h library for it to work, why? (afaik the srand and rand functions are in stdlib)?
  2. in the example the srand function is written the following way:

    srand((unsingned int)time(NULL);
    

我正在使用CodeBlocks,并且没有使用unsigned int 和math库也能正常工作,那么为什么示例中要包含它们?

谢谢!


1
你能够包含指南的链接吗? - Shafik Yaghmour
你试过了吗?如果省略 math.h,编译器会返回什么错误(如果有的话)?这可能会给你一些线索。此外,请查看 time() 返回的类型以及 srand() 期望的内容。 - lorenzog
time_t 的类型是整数还是浮点数? - chux - Reinstate Monica
3个回答

4
函数time返回一个time_t值,而srand需要一个unsigned int参数。如果没有进行强制类型转换,编译器可能会产生警告,并且根据编译器标志的不同,这可能导致编译失败。通常最好避免警告。
你展示的代码行中没有需要包含math.h的内容。可能这个注释是指代码的其他部分?

现在的time_t范围通常比unsigned更大。因此,为了避免警告,最好将类型更改为time_t。这是一个良好的编程实践。+1 - chux - Reinstate Monica
谢谢!因为假期的缘故,我回复有些晚了。 - Medvednic

3
我需要在C语言的srand函数中,使用(unsigned int)将time(null)转换为无符号整型吗?
time()函数返回一个time_t类型的变量,该类型在编译器上对应的类型大小是由实现定义的。你必须查看编译器文档。
除了stdlib.h和time.h库之外,说必须要包含math.h库才能工作,这是真的吗?
对于所发布的代码行,不需要使用math.h。很可能它是用于代码的其他部分。

0

你不需要包含数学库。

这个例子大部分时间都可以工作,但从技术上讲是不正确的,因为将不兼容的类型强制转换是无效的。

唯一正确的方法是对变量time_t的字节进行哈希处理。

time_t t = time( NULL ) ;
char* p = ( char* )&t ; 
unsigned int hash = 0 ;

for( int i = 0 ; i < sizeof( time_t ) ; i++ )  
    hash += p[i] ;

然后在您的srand()函数中使用哈希。

您可以将其转换为char*,然后使用指针。 哈希函数非常简单,您可能想选择更好的函数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接