警告C4244:'argument':从'time_t'转换为'unsigned int',可能丢失数据 - C ++

时间:2012-02-12 04:55:16

标签: c++

我做了一个简单的程序,允许用户选择一些骰子,然后猜测结果...我之前发布了这个代码,但是错误的问题所以它被删除了...现在我不会有任何错误甚至警告这个代码,但由于某种原因这个警告不断弹出,我不知道如何解决它... “警告C4244:'参数':从'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:'参数':从'time_t'转换为'unsigned int',可能丢失数据

4 个答案:

答案 0 :(得分:57)

这是因为在您的系统上,time_t是一个比unsigned int更大的整数类型。

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

因此你得到了警告。你可以用演员来沉默它:

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

在这种情况下,由于您仅使用它来为RNG播种,因此向下(和潜在的数据丢失)并不重要。

答案 1 :(得分:8)

这一行涉及来自time_t的隐式演员,其中time返回unsigned int srand {/ 1}}:

srand ( time(NULL) );

您可以将其改为显式转换:

srand ( static_cast<unsigned int>(time(NULL)) );

答案 2 :(得分:2)

time()返回time_tcan be 32 or 64 bitssrand()unsigned int,即32位。公平地说,你可能不会关心,因为它只被用作随机化的种子。

答案 3 :(得分:1)

这一行涉及来自time_t的隐式转换,该时间返回到signed取的unsigned int:

srand ( time(NULL) );

您可以将其改为显式转换:

srand ( static_cast<unsigned int>(time(NULL)) );
相关问题