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