2015-10-17 102 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'; 
     }