2015-10-17 103 views
-1

我想用1〜10。以下是一個示例程序的範圍內srand()函數函數每次產生五個隨機數的隨機數:生成使用函數srand

#include<stdio.h> 
#include<math.h> 
#define size 10 
int main() 
{ 
    int A[5]; 
    for(int i=0;i<5;i++) 
    { 
     A[i]=srand()%size  
    } 
} 

但是我收到一個錯誤說太函數srand()的參數很少。什麼是解決方案?

+0

如果說有過多的參數,你怎麼想的解決辦法是? http://en.cppreference.com/w/cpp/numeric/random/srand –

+1

'rand'是你正在尋找的功能。 'srand'種子'rand'。 –

+0

@bku_drytt:但提供參數不會解決此問題。 'srand'不應該返回一個值。 – usr2564301

回答

0

srand設置了rand,僞隨機數生成器種子。

更正代碼:

#include <stdio.h> 
#include <math.h> /* Unused header */ 
#include <stdlib.h> /* For `rand` and `srand` */ 
#include <time.h> /* For `time` */ 

#define size 10 

int main() 
{ 
    int A[5]; 

    srand(time(NULL)); /* Seed `rand` with the current time */ 

    for(int i = 0; i < 5; i++) 
    { 
    A[i] = rand() % size; // `rand() % size` generates a number between 0 (inclusive) and 10 (exclusive) 
    } 
} 
0

您必須使用std::rand()而不是std::srand(),但在使用之前,必須使用std::srand()來提供無符號值。像啓動一樣。

看在std :: srand()函數全球化志願服務青年http://en.cppreference.com/w/cpp/numeric/random/srand

/*Seeds the pseudo-random number generator used by std::rand() with the value seed. 
If rand() is used before any calls to srand(), rand() behaves as if it was seeded with srand(1). Each time rand() is seeded with srand(), it must produce the same sequence of values.  
srand() is not guaranteed to be thread-safe. 
*/ 

    #include <cstdlib> 
    #include <iostream> 
    #include <ctime> 


     int main() 
     { 
      std::srand(std::time(0)); //use current time as seed for random generator 
      int random_variable = std::rand(); 
      std::cout << "Random value on [0 " << RAND_MAX << "]: " 
         << random_variable << '\n'; 
     }