警告 C4244:'argument':从 'time_t' 转换为"无符号 int",可能会丢失数据 -- C++
warning C4244: 'argument' : conversion from 'time_t' to 'unsigned int', possible loss of data -- C++
我制作了一个简单的程序,允许用户选择一个骰子数量,然后猜测结果。。。我以前发布过这个代码,但有一个错误的问题,所以它被删除了。。。现在我不能在这个代码上有任何错误甚至警告,但由于某种原因,这个警告不断出现,我不知道如何修复它。。。"警告C4244:'argument':从'time_t'转换为'unsignedint',可能丢失数据"
#include <iostream>
#include <string>
#include <cstdlib>
#include <time.h>
using namespace std;
int choice, dice, random;
int main(){
string decision;
srand ( time(NULL) );
while(decision != "no" || decision != "No")
{
std::cout << "how many dice would you like to use? ";
std::cin >> dice;
std::cout << "guess what number was thrown: ";
std::cin >> choice;
for(int i=0; i<dice;i++){
random = rand() % 6 + 1;
}
if( choice == random){
std::cout << "Congratulations, you got it right! n";
std::cout << "Want to try again?(Yes/No) ";
std::cin >> decision;
} else{
std::cout << "Sorry, the number was " << random << "... better luck next time n" ;
std::cout << "Want to try again?(Yes/No) ";
std::cin >> decision;
}
}
std::cout << "Press ENTER to continue...";
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), 'n' );
return 0;
}
这就是我试图弄清楚的,为什么我会收到这个警告:警告C4244:"argument":从"time_t"转换为"unsigned int",可能丢失数据
这是因为在您的系统中,time_t
是一个比unsigned int
大的整数类型。
- 3返回一个可能是64位整数的CCD_ 4
- CCD_ 5想要一个可能是32位整数的CCD_
因此你得到了警告。你可以通过施法使其静音:
srand ( (unsigned int)time(NULL) );
在这种情况下,下变频(以及潜在的数据丢失)并不重要,因为您只使用它来播种RNG。
此行涉及从time_t
到unsigned int
的隐式强制转换,time
返回到srand
采用的CCD_9:
srand ( time(NULL) );
你可以改为显式转换:
srand ( static_cast<unsigned int>(time(NULL)) );
time()
返回一个time_t
,它可以是32或64位。srand()
取32比特的unsigned int
。公平地说,你可能不会在意,因为它只是用作随机化的种子。
这一行包含一个从time_t到无符号int的隐式强制转换,time_t返回到srand采用的无符号int:
srand ( time(NULL) );
你可以改为显式转换:
srand ( static_cast<unsigned int>(time(NULL)) );
相关文章:
- 防止主数据类型C++的隐式转换
- 用于访问容器<T>数据成员的正确 API
- 嵌套在类中时无法设置成员数据
- 使用流处理接收到的数据
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 在cuda线程之间共享大量常量数据
- C++将文本文件中的数据读取到结构数组中
- 如何在C++中序列化结构数据
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- 在c代码之间共享数据的最佳方式
- 链表,反向函数,数据结构
- 数据成员SFINAE的C++17测试:gcc vs clang
- C++浮点数据类型和字符串数据类型无法子到模板函数中
- 如何对点云数据进行排序
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 尝试通过OCI例程从Oracle获取blob数据,但出现错误:ORA-01008:并非所有变量都绑定
- Cuda C++:设备上的Malloc类,并用来自主机的数据填充它
- 在运行时处理类型擦除的数据-如何不重新发明轮子