2013-01-18 85 views
1

之間的隨機數可能重複:
How to generate a random number from within a range - C生成1到N-1

你將如何產生1和N-1之間的隨機數,其中N是一個數字的用戶打入?

到目前爲止,我的代碼是:

#include <stdio.h> 
#include <stdlib.h> 
int main() 
{ 
    int number = 0; //number variable 
    printf("This program will ask you for a number, an integer, and will print out a random number from the range of your number 1, to N-1.");//output that explains the program's purpose and use to the user. 
    //gets the input 
    fgets(buffer, sizeof(buffer), stdin); 
    sscanf(buffer, "%d", &number); //gets the input and stores it into variable number 

    return (0); 

}

+0

提示:查找返回一個隨機數,使用取模運算符的功能 –

回答

1

嘗試是這樣的: -

unsigned int 
randomr(unsigned int min, unsigned int max) 
{ 
     double x= (double)rand()/RAND_MAX; 

     return (max - min +1)*x+ min; 
} 

退房此鏈接: - http://c-faq.com/lib/randrange.html

0

你需要看看rand。數學和你有一個解決方案。

1

根據你想要數字的「隨機」方式,你可以使用標準libc中的rand()函數。該函數將生成0到RAND_MAX之間的數字。然後您可以通過使用模運算來獲得良好範圍的結果。

注意,此發生器(一個LCG)是既不適合用於加密應用也不科學應用。

如果你想要更合適的發電機,看看發電機,如Mersenne Twister(儘管如此,仍然沒有cryptosecure)。

+1

「不適合加密應用程序或科學應用程序」從問題和上下文的外觀來看,我認爲我們不必擔心這一點。 ;) – Mike

+0

當然,但這只是爲了防止有人會用這個答案的其他東西:-) –