为什么在对随机数生成器进行时间种子设定时会收到可能丢失数据的警告(NULL)

Why do I get a warning about possible loss of data when seeding the random number generator from time(NULL)?

本文关键字:数据 NULL 警告 随机数生成器 时间 定时 种子 为什么      更新时间:2023-10-16

am学习向量,并制作了一段代码,用于选择随机数,我可以在荷兰购买彩票。但是,尽管它在运行,编译器还是警告我"从"time_t"转换为"unsigned int",可能会丢失数据"。

有人能发现是什么原因造成的吗?我甚至没有在这段代码中定义任何无符号int;根据我的理解,默认情况下int i是一个有符号的int。感谢您的真知灼见。

#include <iostream>
#include <vector>
#include <string>
#include <ctime>
using namespace std;
void print_numbers();
string print_color();
int main() {
srand(time(NULL));
print_numbers();
string color = print_color();
cout << color << endl;
system("PAUSE");
return 0;
}
//Fill vector with 6 random integers. 
//
void print_numbers() {
vector<int> lucky_num;
for (int i = 0; i < 6; i++) {
    lucky_num.push_back(1 + rand() % 45);
    cout << lucky_num.at(i) << endl;
}
}
//Select random color from array.
//
string print_color() {
string colors[6] = {"red", "orange", "yellow", "blue", "green", "purple"};
int i = rand()%6;
return colors[i];
}

确切的编译器消息:警告C4244:"argument":从"time_t"转换为"unsigned int",可能会丢失数据。第11行。

由于在特定平台上time_t的大小恰好大于unsigned int,因此会收到这样的警告。从"较大"类型转换为"较小"类型涉及数据的截断和丢失,但在您的特定情况下,这并不重要,因为您只是对随机数生成器进行种子设定,unsigned int溢出应该发生在遥远的将来。

明确地将其投射到unsigned int应该会抑制警告:

srand((unsigned int) time(NULL));

time_t在许多平台上是一个64位值,以防止历元时间最终包装,而unsigned int是32位。

在你的情况下,你不在乎,因为你只是在播种随机数生成器。但在其他代码中,如果您的软件处理的日期超过2038年,则当您转换为32位值时,可能会将time_t截断为2038年之前的32位日期。

time返回一个time_t对象。

srand需要一个无符号整数。

srand(time(NULL));

如果time的返回值超过unsigned int的表示范围,则此行可能溢出,这当然是可能的。

void srand ( unsigned int seed );
time_t time ( time_t * timer );
typedef long int __time_t;

long int与无符号int不同。因此发出警告。

(来自stackoverflow