【问题标题】:C++ Rand Function errorC++ 兰德函数错误
【发布时间】:2013-03-03 01:49:29
【问题描述】:

我正在尝试制作基于文本的角色扮演游戏,目前正在实现 diceroll 功能:

int diceRoll(){
int n;
srand(time(0));
n = rand() % 4;
return n;
}
int main()
{
    int RandNum = diceRoll();
    cout<< "   Randomly generated number: " + RandNum;
    return 0;
}

但它会输出这个:

【问题讨论】:

标签: c++ random


【解决方案1】:

试试:cout &lt;&lt; "Randomly generated number: " &lt;&lt; RandNum;

【讨论】:

  • 谢谢!现在工作得很好
【解决方案2】:

您实际上是在将数字添加到字符串中......这并没有按照您的想法进行。实际上,它计算字符串的地址偏移量,我猜这就是您在开头添加一些空格的原因。你可能想要流插入操作符&lt;&lt;:

cout<< "   Randomly generated number: " << RandNum;

此外,在随机数生成器中调用 srand() 是个坏主意。为什么?因为如果你快速调用它很多次time() 可能每次都返回相同的值,导致rand() 每次都以相同的值作为种子,因此给出相同的结果(也不是很随机)。大多数情况下,您应该在程序开始时调用一次srand()

【讨论】:

    【解决方案3】:

    您通常不应该使用 rand() 和模数。这是一个坏习惯。相反,请使用&lt;random&gt;http://www.cplusplus.com/reference/random/. 或者只是谷歌“c++随机头使用”或类似的东西。

    【讨论】:

    • cplusplus.com 很糟糕,你应该感觉很糟糕
    猜你喜欢
    • 1970-01-01
    • 2020-04-09
    • 1970-01-01
    • 2018-09-10
    • 2016-09-21
    • 2011-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多