2

我想生成一个非常长的整数随机数,我希望它是 224 位随机数。但我能找到的最长的数据类型是 unsigned long long,它是 64 位。首先我这样做了:

#include <iostream>
#include <string>
#include <stdint.h>
#include <stdlib.h>
#include <ctime>
#include "random.h"
int main()
{
    srand(time(0));

    unsigned long long num1 = rand();
    unsigned long long num2 = rand();

    cout<<"1st random number = " << num1 << endl;
    cout<<"2nd random number = " << num2 << endl;

    return 0;
}

我的想法是定义 224 位整数的新数据类型。所以我尝试制作新的 random.h 文件:

class int224 
{
    unsigned int data[7];
}

然后修改了第一个代码:

#include <iostream>
#include <string>
#include <stdint.h>
#include <stdlib.h>
#include <ctime>
#include "random.h"
int main()
{
    srand(time(0));

    int224 num1 = rand();
    int224 num2 = rand();

    cout<<"1st random number = " << num1 << endl;
    cout<<"2nd random number = " << num2 << endl;

    return 0;
}

但是它返回了错误,也许我在定义新数据类型时犯了一个错误,感谢任何帮助。谢谢你。

4

4 回答 4

1

As you have an array of 7 defined in the class, you will have to call the rand function 7 time to initialize each element.

Also if you want your numbers to be unsigned then it is fine but if you want them to be signed then take care that while accessing the numbers, you cast the first 6 as unsigned and the last one as signed.

于 2013-07-30T11:36:27.233 回答
1

您没有生成随机的函数,int224并且编译器不知道该类。

您可以在中创建自己的Rand()函数int224并使用它。该函数将在数组的每个单元格中放入随机数

于 2013-07-30T11:23:33.053 回答
1

它不能那样工作。内置的 rand 函数返回 anint并且您不能通过仅将结果分配给更大的值来使其返回更大的值。您将必须实现更复杂的逻辑并使用一些调用rand来初始化结果中的不同后续位。

于 2013-07-30T11:23:45.857 回答
1

我想出了以下内容,不确定这是否适合您

#include <iostream>
#include <chrono>
#include <random>

struct int224 
{
    unsigned int data[7];

    int224 operator+(int224);
    int224 operator-(int224);

    int224 ()
    {
     unsigned seed =
         std::chrono::system_clock::now().time_since_epoch().count();

        std::minstd_rand0 mygen (seed); 

      for(auto i=0;i<7;i++)
        data[i]=mygen();    
    }

    friend std::ostream& operator<<(std::ostream&, const int224&);
};

std::ostream& operator<<(std::ostream& os, const int224& r)
{
    for(auto i=0;i<7;i++)
        os<<r.data[i];
    return os;
}

int main ()
{

  int224 r;
  std::cout<<r<<std::endl;

  int224 j;
  std::cout<<j;

  return 0;
}
于 2013-07-30T12:02:27.147 回答