【问题标题】:'rand' function in C++?C ++中的'rand'函数?
【发布时间】:2014-11-05 22:22:45
【问题描述】:

我正在尝试制作一个死亡预测器,让你的角色随着你的进步而随机死亡。我要让它有多次死亡的机会,以及随着年龄的增长而增加的机会。如何修复这个基本的 rand 函数,使其 int RandomFactor 有一个 1-20 的数字并随机激活以杀死你(对不起,如果这听起来很残忍)?

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
#include <Windows.h>
#include <stdlib.h>
#include <time.h>

using namespace std;

int main() {
    srand(time(NULL));
    int RandomFactor;
    RandomFactor = rand();
    20 % 1;

    for (double count = 0; count < 20; count++) {
        if (count < 20) {
            Sleep(360);
            cout << "\n\t\t\tIt's your birthday! You turned: " << count;
        } 
        else
            if (RandomFactor == 1) {
                cout << "\n\n\n\t\t\tBANG! You're dead!";
            }
    }

    cout << "\n\n\n\t\t\t  ";

    return 0;
}

【问题讨论】:

  • 代替RandomFactor = rand(); 20 % 1;试试RandomFactor = rand() % 20;
  • 3 IntelliSense:预期为 ';' c:\Users\Parent\Desktop\DeathPredictionv1\DeathPredictionv1\DeathPredictionv1.cpp 18 24 DeathPredictionv1 如果我这样做,这就是我收到的错误消息。 :(
  • 智能感知可能是智能的,但它不是通灵的。它无法预测您何时要进行计算。

标签: c++ loops if-statement for-loop random


【解决方案1】:

rand() 后面不应该有分号。试试 RandomFactor = rand() 20 % 1;

【讨论】:

  • -1 这肯定会导致语法错误。
【解决方案2】:

C++ 允许你随意丢弃值,所以当你这样做时

20 % 1;

它不会抱怨,因为它会计算它并简单地抛出值。

也许你的意思实际上是:

RandomFactor = rand() % 20;

但是,这将导致 [0, 19] 范围内的数字,因此您可能想要添加 1:

RandomFactor = (rand() % 20) + 1

所以现在范围的两端都将增加 1,导致 [1, 20] 包含在内。


另外,if 语句

if(count < 20)

在您循环时将始终为真(毕竟循环条件),因此else if 将永远不会运行。

【讨论】:

  • 我还要说原始实现似乎没有实现目标,因为对 rand() 的调用是在循环之外,所以每次循环迭代都会有相同的值。要么每个人都死了,要么没有人是
  • @rdowell 或许RandomFactor 正在计算是否会有僵尸末日,在这种情况下这是正确的。谁说的?
【解决方案3】:

您可以使用rand % 20,但它不会真正统一,它会包含偏见。您在 C++ 中的更好选择是使用 std::uniform_int_distribution&lt;&gt; 这种方式

#include <random>
#include <iostream>

int main()
{
    std::random_device rd;
    std::mt19937 gen( rd());
    std::uniform_int_distribution<> dis( 1, 20);

    for ( int n=0; n<10; ++n)
        std::cout << dis(gen) << ' ';
    std::cout << '\n';
}

您可以阅读this 了解更多关于rand() % x 引入的偏见。

【讨论】:

  • 除统计和加密之外的几乎所有事物都可以接受这种规模的偏差:低数字仅比高数字高 0.0061012812%。
  • 我不确定您的结果,我们正在讨论一般情况
  • @MooingDuck:如果语言已经支持更好的随机性,为什么还要满足于劣质模式?另请注意,此示例种子的值如何可能提供比time() 更多的随机性(对于不同的线程/集群节点/...,内部精度可能相同)。
  • @BenjaminBannier:因为我永远无法回忆起这一代人的所有细节,但永远记得rand():/
  • @0d0a:你提到了rand()%20,还有一个替代方案,所以我给了你一个赞成票。 RAND_MAX32768 或更高,所以最坏的情况下,0-7 被选中 1639 次,8-19 被选中 1638 次(8*1639+8*1638=32768)。然后 1639/1638-1 表明低数字比高数字多 0.061050061%。
【解决方案4】:

尝试使用drand(),它将返回一个介于 0 和 1 之间的统一数字,然后您可以对其进行缩放。您可以使用srand48(seed) 对其进行初始化。例如,如果您希望有 20% 的机会触发,您可以这样做:

 if( drand() <= 0.05f ) // (5% chance)
     // do something

或者

int randomNumber = ceil( drand()*20 ); 
// creates a uniform distribution between 1 and 20, inclusive

【讨论】:

    猜你喜欢
    • 2012-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多