为什么在对随机数生成器进行时间种子设定时会收到可能丢失数据的警告(NULL)
Why do I get a warning about possible loss of data when seeding the random number generator from time(NULL)?
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
相关文章:
- 防止主数据类型C++的隐式转换
- 当字段可以为null时,如何使用C++接口在Avro中写入数据
- ClassTemplateSpecializationDecl 的定义数据为 null
- = NULL,在 c++98 中初始化非静态数据成员
- 如何在忽略 null 的同时将数据从 char [] 复制到常量字符 *
- Winsock2 tcp/ip-一些数据包被忽略,可能是由于前一个数据包的null终止符
- 从SQL Server返回C++本机客户端中的NULL数据类型
- 如何将数据发送到QT中打开的tty0tty null调制解调器模拟器端口
- 在 Matlab .mat 文件中读取:变量的秩和变暗正确,但数据为 NULL
- 返回NULL与返回没有数据的obj
- 调用不访问 null 对象指针上数据的方法有时有效,有时崩溃。为什么它不总是崩溃?
- 数据在null节点中的链表
- 为什么imread()总是返回null数据
- 使用迭代最近点(ICP)时,如何在点云库(PCL)中标记NULL数据
- 在调试构建中,数据突然变为NULL
- 为什么在对随机数生成器进行时间种子设定时会收到可能丢失数据的警告(NULL)
- 加密数据中的Null字符
- 将字符串内带有 NULL 字符的字符串数据复制到字符数组
- 正在使用生成器模式的构造函数中将指针类型的成员数据初始化为NULL
- 为什么数据实例在默认情况下不为 NULL?