2017-04-10 42 views
-2

我正在寫一個使用c語言的基本加密程序。在這一點上,我想得到一個隨機數字形式的特定範圍說(97至122)。我在一些編程網站上看到了這個程序。如何在特定範圍內打印隨機值?

int main(void) 
{ 
    int c, n; 

    printf("Ten random numbers in [1,100]\n"); 

    for (c = 1; c <= 10; c++) 
    { 
    n = rand() % 100; 
    printf("%d\n", n); 
    } 

} 

但它打印從1到100 在Python中,我們與rand()的功能,例如的幫助下實現它的隨機值:r = random.randint(97, 122)。那麼有沒有什麼辦法可以在c程序中這樣實現。

+1

是的。最簡單的方法**和錯誤的**,將寫入'97 + rand()%(122-97)'。爲了學習的目的,這就夠了。對於嚴重的加密[嚴格加密的第一條規則是「不要滾動你自己的」],你需要一個平坦分佈的函數,*小寫範圍*不是。 – LSerni

+1

'rand()'不是密碼安全的。從/ dev/urandom讀取,使用類似'arc4random'的東西,或者從真正的隨機源讀取。 – midor

+0

@LSerni我剛剛進入密碼,謝謝你,我記住了。 – pkarthicbz

回答

0

找出97到122之間有多少個數字(提示 - 注意偏差錯誤),選擇一個介於0和x之間的隨機數字,然後添加97。

0
#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 
#include <time.h> 

int main() 
{ 
    int n = 0; 
    srand(time(NULL)); // seed for rand 

    for (int c = 1; c <= 10; c++) 
    { 
    n = rand() % 25 + 97; // rand() gives you a number between 0 and 24 and then add 98 to get a number between 97 and 122 
    printf("%d\n", n); 
    } 
} 
+1

添加97然後,不是98 ;-) – LSerni

+0

錯過類型抱歉我編輯它 – RomMer

相關問題