2014-09-13 70 views
2

我一直在試圖編寫一個用於生成隨機值的小C函數。問題是每次在for循環中調用函數時它都會返回相同的值。我明白問題是srand是用NULL播種的。我想知道的是如何糾正它,因此在for循環的每次迭代中函數都會返回一個不同的值。下面的代碼:如何使隨機值函數每次返回不同的值

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

int randInt(int,int); 

void main(){ 

    int min=100, max=200,i=0; 

    for(i;i<11;i++){ printf("%d \n",randInt(min,max)); } 

} 


int randInt(int a,int b){ 

    srand(time(NULL)); 
    int randValue; 
    randValue=1+(int)rand()%(b-a+1); 
    return randValue; 

} 

請讓我知道,如果你有一個解決方案,也可以張貼一些參考的解決方案。先謝謝你 !

編輯:遇到問題#2,在將srand(time(NULL))換成main後,現在每次迭代都會在我的範圍內產生數字,即最初我想要的數字在100到200之間,但它也包含0和100。這與randValue=a+(int)rand()%(b-a+1);解決作爲意見提出

+5

不要在隨機函數內調用'srand'。 – 2014-09-13 10:41:23

+0

展開退休忍者的評論。 srand用於(一次)初始化,然後rand用於檢索值。 – 2014-09-13 10:46:51

+0

謝謝,忍者,它的工作!現在,再一個小問題 - 我試圖產生從100到200的數字,但函數生成值在100以下。我該如何解決這個問題? – 2014-09-13 10:47:19

回答

1

srand(time(NULL));main只是{

後,在100-200範圍內生成隨機數,而不是加1,加100或a

randValue=(int)rand()%(b-a+1); 

因此,它看起來像:

randValue=(int)rand()%(b-a+1)+100; 
+1

這不會解決他的第二個問題 – Quest 2014-09-13 10:59:08

+1

他的第二個問題是什麼?沒有什麼更多的問題 – 2014-09-13 10:59:55

+0

你應該真的閱讀問題 – Quest 2014-09-13 11:00:32

0

我使用minmax INSEAD的ab。它是你的代碼的未來讀者更好地

  1. 你應該在初始化例如,在你的main()
  2. 你可能想min + rand() % (max - min + 1)代替rand()%(b-a+1)
+0

-1你不能在'randInt'函數中使用'min'或'max',因爲它們是局部變量 – 2014-09-13 11:15:46

+0

@CoolGuy ups仔細閱讀我**做過**提及 – Quest 2014-09-13 11:28:54

+0

啊,你編輯了它。 – 2014-09-13 11:29:48

1

使用srand(time(NULL))只有一次這樣每次打印隨機值在100-200之間:

#include<stdio.h> 
#include<stdlib.h> 
#include<time.h> 
int randInt(int a,int b) 
{ 
    int randValue; 
    randValue = (rand() % (b-a+1)) + a; 
    return randValue; 
} 

int main(void) { 
    int r=0, i = 0; 

    srand(time(NULL)); 
    do 
    { 
     r = randInt(100,200); 
     printf("%d\n",r); 
     i++; 
    }while(i < 11); 
    puts("Done!"); 

    return 0; 
} 
+0

刪除了我以前的評論+1 – Quest 2014-09-13 11:27:42

+0

@chux:謝謝:) – user1336087 2014-09-13 14:23:49