【问题标题】:Why is srand() not being stored in my variable?为什么 srand() 没有存储在我的变量中?
【发布时间】:2016-08-15 03:57:09
【问题描述】:

我正在尝试制作的这个初学者程序基本上是一个生成真正随机数并且“玩家”必须猜测数字的程序。计算机会响应“太高”或“太低”,直到玩家猜对了数字。

我从某个网站获得了这个程序的想法,并认为我应该继续使用它。这是我的第二个程序——我的第一个程序是一个简单的 I/O 程序。

这是我的代码:

// BracketingSearch.cpp

#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <string>
#include <ctime>
#include <istream>
#include <fstream>
using namespace std;

int main() 
{

int x = srand(time(0));
cout << x << endl;
for (int x = 1; x <= 10; x++) {
    cout << 1 + (rand() % 100) << endl;
}
string stall;
getline(cin, stall);
}

旁注: 我认为我不需要那么多标题;我仍在使用 c++ 库。 请尽可能多地批评我的代码。我渴望学习编程! string stall 只是为了让我的控制台应用程序暂停输入,以便我可以看到结果。

感谢所有可以提供帮助的人! -迈克

【问题讨论】:

  • 您似乎有 2 个不同的问题:“为什么 srand 没有存储在我的变量中”和“请尽可能多地批评我的代码”。您在寻找code review 吗?请澄清。
  • srand 的返回类型为void。我很惊讶你的编译器没有抱怨int x = srand(time(0));
  • 函数srand()没有返回值。见这里:cplusplus.com/reference/cstdlib/srand 编辑:看起来@RSahu 快了几秒钟。
  • 而不是srandrand 看看使用std::uniform_int_distribution
  • 这是否通过了编译器? srand 确实返回 void,编译器不应允许将此值分配给 x。

标签: c++ variables random srand


【解决方案1】:

srand(time(0)) 种子rand() 生成的随机数。它的返回类型是void。 void 类型不能存储在整数类型变量中。

有关srand() 的更多信息,请参阅here

【讨论】:

  • 您如何建议我为该程序存储 void 数据类型?我跟着那个链接,它有很好的建议。谢谢!
  • 为什么需要将srand(time(0)) 存储在变量中?简单的srand(time(0)) 也可以完成这项工作。
  • 我尝试在整个程序中使用rand(),似乎每次放置它时该函数都会改变它的值。
  • 当使用srand(time(0)) 时,它不会让我使用cout &lt;&lt; 打印任何内容或使用!=&gt; 运算符。看来这是因为srand() 是一个void 类型,而rand() 是一个int 数据类型。有什么建议吗?
【解决方案2】:

我重写了程序以使用所需的最少标题。由于我认为这是作业,所以我将原始错误留在原处,但将 gcc 的错误输出放在这里。

#include <iostream>
#include <cstdlib>
#include <ctime>

// this is a personal thing, but I avoid "using namespace std;"
// in any file, since it makes it less clear where some symbols
// came from

int main() 
{
    int x = std::srand(std::time(0)); // line 11
    std::cout << x << std::endl;
    for (int x = 1; x <= 10; x++) {
        std::cout << 1 + (std::rand() % 100) << std::endl;
    }

    // Windows folklore -- you should better switch your ide to not close
    // the terminal after the program was run
    std::cin.get();
}

g++ -Wall foo.cpp的输出:

foo.cpp: In function 'int main()':
foo.cpp:11:40: error: void value not ignored as it ought to be
         int x = std::srand(std::time(0));
                                        ^

【讨论】:

  • 使用 Visual C++,这是我的错误:a value of type "void" cannot be used to initialize an entity of type "int"initializing: cannot convert from 'void' to 'int'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-27
  • 2019-01-17
  • 1970-01-01
  • 2022-06-11
  • 1970-01-01
相关资源
最近更新 更多