Dan*_*atz 5 c++ compiler-errors compiler-warnings
我正在学习矢量并制作了一些代码来选择我可以在荷兰购买彩票的随机数字.但是虽然它运行,编译器警告我'从'time_t'转换为'unsigned int,可能会丢失数据'.
有人能发现造成这种情况的原因吗?我甚至没有在这段代码中定义任何unsigned int; 我理解默认情况下,int是一个signed 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];
}
Run Code Online (Sandbox Code Playgroud)
确切的编译器消息:警告C4244:'argument':从'time_t'转换为'unsigned int',可能丢失数据.第11行.
因为time_t恰好比unsigned int你的特定平台更大,所以你会收到这样的警告.从"较大"类型转换为"较小"类型涉及截断和丢失数据,但在您的特定情况下它并不重要,因为您只是播种随机数生成器并且溢出unsigned int应该出现在日期中很远的未来.
unsigned int明确地将其强制转换应该禁止警告:
srand((unsigned int) time(NULL));
Run Code Online (Sandbox Code Playgroud)