c++ - 警告 C4244 : 'argument' : conversion from 'time_t' to 'unsigned int' , 可能丢失数据 -- C++

标签 c++

我制作了一个简单的程序,允许用户选择一些骰子然后猜测结果......我之前发布了这段代码,但有错误的问题,所以它被删除了......现在我不能有任何错误甚至此代码上的警告,但由于某种原因,此警告不断弹出,我不知道如何修复它... “警告 C4244:'argument':从 'time_t' 转换为 'unsigned int',可能丢失数据”

#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 更大的整数类型。

  • time() 返回一个可能是 64 位整数的 time_t
  • srand() 想要一个可能是 32 位整数的 unsigned int

因此您会收到警告。您可以通过 Actor 使其静音:

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

在这种情况下,向下转换(以及潜在的数据丢失)并不重要,因为您只是用它来播种 RNG。

关于c++ - 警告 C4244 : 'argument' : conversion from 'time_t' to 'unsigned int' , 可能丢失数据 -- C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9246536/

相关文章:

c++ - 从文本文件中读取矩阵并在 C++ 中使用一列的数字

c++ - 从文件中读入结构数组

c++ - Fortran 中 REAL(KIND=real_normal) 的 C 等效类型是什么?

iphone - 格式与字符串 : Cocos2d-x passing in a CCString

c++ - 如何使函数在不同时间调用时返回不同的字符串? C++

c++ - 为什么我的 .cpp 文件没有被处理?

c++ - const 引用并创建拷贝

c++ - 如何在只有 protected 或私有(private)构造函数的类上调用::std::make_shared?

c++ - 如何在 std::function 的签名上重载构造函数?

c++ - 编程 ftp : how to abort file transfer?