2014-02-26 202 views
1

新手在C這裏。 我試圖每次運行一個程序時爲變量賦予不同的值。 我有這樣的代碼:C - 生成隨機數

#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 
#define ADD 1 
#define SUB 2 
#define MUL 3 
#define DIV 4 

int main(void) 
{ 
    double out; 
    int choice; 
    float x, y; 
    printf("Welcome to our first calculator program!\n"); 
    printf("===========================\n"); 
    printf("Please insert 2 numbers:\n"); 
    scanf("%f%f", &x, &y); 
    choice = 1 + srand(time(NULL)) % 4; 
    if(choice == ADD) 
      out = x + y; 
    else if(choice == SUB) 
      out = x - y; 
    else if(choice == MUL) 
      out = x * y; 
    else 
    { 
      if(y != 0) 
        out = x/y; 
      else 
      { 
        out = 0; 
        fprintf(stderr, "error"); 
        return 1; 
      } 
    } 
    printf("The outcome is: %0.2lf\n", out); 
    return 0; 
} 

但它總是給我4選擇。我不明白爲什麼......

你能幫助我嗎?謝謝。

+1

你肯定* *代碼彙編? 'srand'(或者「seed random」)應該有一個* void *返回類型,'rand'應該用來得到* actual *隨機數。 – user2864740

+1

@ user2864740'gcc版本4.7.2(Debian 4.7.2-5)'抱怨'錯誤:void值不會被忽略,因爲它應該是'。 –

+1

@ user2864740 Visual Studio 2010也抱怨:'錯誤C2296:'%':非法,左操作數有類型'void'' ..不知道哪個編譯器允許這個:)? –

回答

3

現在您呼叫srand和期待的隨機數。通過調用srandhttp://www.cplusplus.com/reference/cstdlib/srand/

int main() 
{ 
    printf ("First number: %d\n", rand()%100); 
    srand (time(NULL)); 
    printf ("Random number: %d\n", rand()%100); 
    srand (1); 
    printf ("Again the first number: %d\n", rand()%100); 

    return 0; 
} 

看你怎麼種子,然後檢索: 你應該通過調用srand,然後調用rand獲得隨機數:)

取自用法示例種子熵池從rand

隨機整數你需要這樣做:

srand(time(NULL)); 
choice = 1 + rand() % 4; 

,而不是這樣的:

choice = 1 + srand(time(NULL)) % 4; 
1

您需要種子隨機數發生器 - 請參閱srand-http://linux.die.net/man/3/srand

使用類似當前時間的東西。

然後使用rand獲得一個隨機數