我想每次使用1到10范围内的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 :(得分:0)
您必须使用std::rand()
而不是std::srand()
,但在使用之前,您必须使用std::srand()
提供无符号值。像启蒙一样。
查看std :: srand()referance 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';
}
答案 1 :(得分:0)
更正后的代码:
#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)
}
}