【问题标题】:Problems with srand(), C++srand() 的问题,C++
【发布时间】:2010-11-12 03:58:55
【问题描述】:

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

我收到此错误

39 C:\Dev-Cpp\srand_prg.cpp void value not ignored as it ought to be 

使用此代码

#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 ; }

}

【问题讨论】:

  • 下面有很多很好的答案。为了将来参考,编译器消息“void value not ignored as it should be”告诉您:“您正在使用定义为不返回任何内容的函数的结果('void')”。这通常意味着您应该查看有关如何使用该功能的文档,因为您尝试的内容不正确。

标签: c++ srand


【解决方案1】:

srand 不返回随机数,它只是重新设置随机数生成器的种子。之后拨打rand实际获取号码:

srand(9);
rand_int = rand();

【讨论】:

    【解决方案2】:

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

    如果你不知道要摘什么种子,就用当前时间:

    srand(static_cast<unsigned int>(time(0))); // include <ctime> to use time()
    

    【讨论】:

      【解决方案3】:

      这样称呼它。

      srand(9);
      rand_int = rand();
      

      【讨论】:

        【解决方案4】:

        您错误地使用了srand,该特定功能用于设置种子以供以后调用rand

        基本思路是用不确定的种子调用srand一次,然后连续调用rand得到一个数字序列。比如:

        srand (time (0));
        for (int i = 0; i < 10; i++)
            cout << (rand() % 10);
        

        这应该会给你一些介于 0 和 9 之间的随机数。

        您通常不会将种子设置为特定值,除非您正在测试或出于其他原因想要相同的数字序列。您也不要在每次调用 rand 之前设置种子,因为您可能会重复获得相同的号码。

        所以你的特定 while 循环会更像:

        srand (9); // or use time(0) for different sequence each time.
        while (close != "y") {  // for 1 thru 9 inclusive.
            rand_int = rand() % 9 + 1;
            cout << rand_int << endl;
        
            cout << "Do you wish to exit the program? [y/n]? ";
            cin >> close;
        }
        

        【讨论】:

          【解决方案5】:

          srand 返回 void 函数并且不返回值。

          Here你可以看到更多。您只需要调用 srand(9) 并在此之后获取 rand() 的值,就像 J-16 SDiZ 指出的那样,谁会因此而获得支持:)

          【讨论】:

            猜你喜欢
            • 2014-12-28
            • 2021-01-23
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-12-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多