srand man
表示srand
的参数为unsignd int, ,但是在不使用转换的情况下使用时,编译不会发生抱怨。 如果你不使用 (unsigned int)
铸造有任何出错的机会?或者没有区别,因为编译器 总是会隐式转换它?如果srand函数的参数是一个负int,幕后会发生什么?
作为一个例子,以下代码:
#include<stdio.h>
#include<stdlib.h>
int
main(void)
{
int num, x;
x = -2;
srand(x);
num = rand() % 100000;
printf("%d\n", num);
return 0;
}
此代码的打印是:
32
我将假定编译器将隐式转换int
类型的变量x在unsigned int
。 这次转换会发生什么? 如果转换将变量(类型为int
)转换为unsigned int
,该值与其他编号为 的值相同,则在生成种子后它们将相同。 换句话说:
int x = -2;
int y = 546; // the number 546 is just an example !
int num_x = srand(-2);
int num_y = srand(546);
而且,behinde场景,num_x
等于num_y
。
这个疑问出现在我对品种有负面影响的时候,我怀疑这个种子是否是唯一的。我认为不是,因为为例,代码如下:
#include<stdio.h>
#include<stdlib.h>
int
main(void)
{
int t, num;
t = -6;
printf("%u\n", t); // prints the variable t as unsigned (implicitly converted)
srand(t);
num = rand() % 100000;
printf("Random number: %d\n", num);
srand(4294967290); // the number 4294967290 is how the int number -6 looks like when converted in unsigned int
num = rand() % 100000;
printf("New random number: %d\n", num);
return 0;
}
它的输出:
4294967290
Random number: 19
New random number: 19
所以,总是负数转换后,将这样的表现? 我该如何照顾这个?
还有一个问题你可能知道,我观察到,当我尝试将一个大于它所支持的“int”变量赋值给一个“int”变量时,会出现类似的行为。那么,什么是计算知道它将存储在变量上的值是多少,我试图存储一个比它支持的值更大的值?这将帮助我了解它是如何实施的。 – ViniciusArruda 2014-08-31 06:17:56
首先感谢这个链接,对我会有很大的帮助,但是,对于坚持我抱歉,我读了文档,但没有找到显示数字如何存储的情况,case大于类型支持。我希望能够详细报告会议6.3.1.3。 – ViniciusArruda 2014-09-01 13:17:33
我想我明白了。我在网上发现了一些关于整数溢出的内容。那么,在这种情况下,这就是我的意思?或仅当涉及算术时存在整数溢出? [整数溢出](http://en.wikipedia.org/wiki/Integer_overflow)和[未定义的行为](http://en.wikipedia.org/wiki/Undefined_behavior) – ViniciusArruda 2014-09-01 13:56:55