首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >srand()、C++的问题

srand()、C++的问题
EN

Stack Overflow用户
提问于 2010-11-12 11:58:56
回答 5查看 3.9K关注 0票数 1

我正在尝试编写一个使用种子生成伪随机数的程序。然而,我遇到了一些问题。

我得到了这个错误

代码语言:javascript
复制
39 C:\Dev-Cpp\srand_prg.cpp void value not ignored as it ought to be 

使用以下代码

代码语言:javascript
复制
#include <iostream>
#include <iomanip>
#include <sstream> 
#include <limits>
#include <stdio.h>

using namespace std ;

int main(){
    int rand_int;
    string close ;

    close == "y" ;

    cout << endl << endl ;
    cout << "\t ___________________________________" << endl ;
    cout << "\t|                                   |" << endl ;
    cout << "\t|   Pseudorandom Number Game!       |" << endl ;
    cout << "\t|___________________________________|" << endl ;
    cout << endl << endl ;

    while ( close != "y" ){

        rand_int = srand(9);
        cout << rand_int << endl ;

        cout << "  Do you wish to exit the program? [y/n]     " ;
        cin >> close ; }

}
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2010-11-12 12:01:35

srand不会返回随机数,它只是重新设定随机数生成器的种子。之后调用rand来实际获取一个数字:

代码语言:javascript
复制
srand(9);
rand_int = rand();
票数 8
EN

Stack Overflow用户

发布于 2010-11-12 12:01:58

srand()生成一个种子(用于初始化随机数生成器的数字),并且必须在每个进程中调用一次。rand()是您要查找的函数。

如果您不知道要选择哪个种子,请使用当前时间:

代码语言:javascript
复制
srand(static_cast<unsigned int>(time(0))); // include <ctime> to use time()
票数 4
EN

Stack Overflow用户

发布于 2010-11-12 12:01:53

这么说吧。

代码语言:javascript
复制
srand(9);
rand_int = rand();
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4161501

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档