C++ 为什么在从时间(NULL)开始设定随机数生成器种子时,我会收到关于可能丢失数据的警告?
我正在学习向量,并编写了一段代码,用来选择随机数,我可以用它在荷兰买彩票。但是,尽管它运行,编译器警告我“从“time\t”转换为“unsigned int,可能会丢失数据” 有人能发现这是什么原因吗?我甚至没有在这段代码中定义任何无符号int;据我所知,int i默认为带符号的int。谢谢你的洞察力C++ 为什么在从时间(NULL)开始设定随机数生成器种子时,我会收到关于可能丢失数据的警告?,c++,compiler-errors,compiler-warnings,C++,Compiler Errors,Compiler Warnings,我正在学习向量,并编写了一段代码,用来选择随机数,我可以用它在荷兰买彩票。但是,尽管它运行,编译器警告我“从“time\t”转换为“unsigned int,可能会丢失数据” 有人能发现这是什么原因吗?我甚至没有在这段代码中定义任何无符号int;据我所知,int i默认为带符号的int。谢谢你的洞察力 #include <iostream> #include <vector> #include <string> #include <ctime> u
#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];
}
#包括
#包括
#包括
#包括
使用名称空间std;
作废打印号码();
字符串打印颜色();
int main(){
srand(时间(空));
打印数字();
字符串颜色=打印颜色();
couttime\u t
在许多平台上是一个64位的值,以防止纪元时间最终换行,而unsigned int
为32位
在你的情况下,你不在乎,因为你只是在播种随机数生成器。但在其他代码中,如果你的软件处理日期,当你将时间转换为32位值时,你可以将时间截断为2038年之前的32位日期。因为时间恰好比无符号整数大在您的特定平台上,您会收到这样一个警告。从“较大”类型转换为“较小”类型会导致数据截断和丢失,但在您的特定情况下,这并不重要,因为您只是在播种随机数生成器,溢出的unsigned int
应该在很遥远的将来的某个日期发生
将其显式转换为unsigned int应抑制警告:
srand((unsigned int) time(NULL));
srand(time(NULL));
返回一个time\t
对象
应为无符号整数
srand(time(NULL));
如果time
的返回值超过无符号int
的表示范围,则此行可能溢出,这当然是可能的
void srand ( unsigned int seed );
time_t time ( time_t * timer );
typedef long int __time_t;
长整型与无符号整型不同。因此出现警告
(从中,当我们不知道确切的编译器消息和代码行时,猜测是非常令人兴奋的。然而,关于荷兰彩票的信息真的很有帮助:)警告消息给了你一行,你应该在帖子中提到这一重要信息(最好是完整的警告消息)。警告将出现在行的srand(time(NULL))“这是唯一一个谈论时间的人。对于未来来说,行号确实会有帮助。有人知道荷兰彩票抽奖中使用的随机数种子吗?它真的会帮我:)