我想將我生成的一個隨機數傳遞給一個int數組。我得到的東西,但它不正確。如何把隨機數放在int數組中C
由於提前,
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int i, n;
time_t t;
n = 5;
int haystack [n];
/* Intializes random number generator */
srand((unsigned) time(&t));
/* Print 5 random numbers from 0 to 50 */
for(i = 0 ; i < n ; i++)
{
printf("%d\n", rand() % 50);
haystack[i] = rand();
printf("%d\n", haystack[i]);
}
return(0);
}
什麼是_not right_? – LPs
int haystackp []打印數字,但不是我用srand時間和rand生成的數字,直到數字50爲止。它用自己的種子生成自己的數字。 – Bejns
你正在調用rand()兩次,你會得到兩個不同的隨機數。如果您想重複使用隨機數,請將其存儲在變量中,並在打印和賦值語句中重複使用。 – dubes