警告 C4244:'argument':从 'time_t' 转换为"无符号 int",可能会丢失数据 -- C++

warning C4244: 'argument' : conversion from 'time_t' to 'unsigned int', possible loss of data -- C++

本文关键字:数据 C++ int argument C4244 time 警告 转换 无符号      更新时间:2023-10-16

我制作了一个简单的程序,允许用户选择一个骰子数量,然后猜测结果。。。我以前发布过这个代码,但有一个错误的问题,所以它被删除了。。。现在我不能在这个代码上有任何错误甚至警告,但由于某种原因,这个警告不断出现,我不知道如何修复它。。。"警告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_tunsigned 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)) );