c++中不允许的函数错误

Srand not an allowed function error in c++

本文关键字:函数 错误 不允许 c++      更新时间:2023-10-16

我刚刚开始学习c++,所以我的问题可能会被缩小。

谁能解释一下srand的功能?
此外,是否有一个更简单,不使用printf函数的rand替代(除了rand) ?

我正在使用这个代码:

#include <stdio.h>      /* printf, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */
#include <iostream.h>
#include <conio.h>
#include <string>
#include <math>
#include <ctype>
int main ()
{
float a;
start:  
  a=srand (time(NULL));
cout<<a;
getch();
goto start;
}

提供了以下错误:
1.

任何帮助都会很感激。:)

srand()不返回值。它的功能和你想的不一样。它为随机数生成器提供种子,但不生成随机数。

您正在寻找rand(),尽管这不是在c++ 11中生成随机数的最佳方式。

土地种子。我相信你想试试

int main ()
{
    float a;
    srand(time(NULL));
    while(true)
    {  
        a=rand();
        cout<<a;
        getch();
    }
}

虽然rand返回int而不是float,但如果您希望生成一个随机的float,则需要额外的工作。