在c ++中生成更好的随机数的测量时间

问题描述 投票:0回答:2

我正在自学编程,作为一个挑战,我试图用c ++创建一个简单的文本战斗系统。我使用rand()函数生成伪随机数。问题是,每次您运行该程序时它们都是相同的。例如如果num1在第一轮中是1,在第二轮中是0,则是0、1、0、1、1、1等,如果关闭程序并重新打开,它将始终为1、0、0、1、0 ,1、1、1 ...然后,我查找了如何测量时间。我想使用一个整数来表示玩家输入特定字符串所花费的时间。我完全按照教程进行操作(除了我对变量的命名不同)。它不起作用。谁能帮我解释一下它的语法吗?我编写了一个简单的程序,精确地表示了我所做的事情,因此您不必遍历整个战斗系统的冗长且无关紧要的代码。我查找了这样的问题,但没有任何效果。

#include <iostream>
#include <chrono>


using namespace std;


int main()
{
    auto time1 = std::chrono::high_resolution_clock::now();
    cout << "enter a character:" << endl;
    char blob;
    cin >> blob;
    auto time2 = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double, std::milli> time = timer2 - timer1;
    cout << time;

    return 0;
}
c++ random time chrono measure
2个回答
0
投票

如果您不使用rand()函数,则需要先使用“种子”调用srand这是一个例子:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main () {
   int i, n;
   time_t t;

   n = 5;

   /* Intializes random number generator */
   srand((unsigned) time(&t));

   /* Print 5 random numbers from 0 to 50 */
   for( i = 0 ; i < n ; i++ ) {
      printf("%d\n", rand() % 50);
   }

   return(0);
}

但就像人们在评论中写的是c样式代码而不是CPP这与CPP一起使用

#include <random>
#include <iostream>

int main()
{
    std::random_device dev;
    std::mt19937 rng(dev());
    std::uniform_int_distribution<std::mt19937::result_type> dist6(1,6); // distribution in range [1, 6]

    std::cout << dist6(rng) << std::endl;
}

How to generate a random number in C++?


0
投票

您的代码由于3个原因而无法正常工作:

  • 变量名中的错别字:将timer1timer2分别更改为time1time2
  • 使用duration_cast代替duration_cast
  • 使用duration方法。

duration返回您调用的类型的滴答数它。

这里是完成的代码:

count()
© www.soinside.com 2019 - 2024. All rights reserved.