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

Gal*_*aum 23 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;
}
Run Code Online (Sandbox Code Playgroud)

这就是我想弄清楚的,为什么我会收到这个警告:警告C4244:'argument':从'time_t'转换为'unsigned int',可能会丢失数据

Mys*_*ial 59

那是因为在你的系统上,time_t是一个比它更大的整数类型unsigned int.

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

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

srand ( (unsigned int)time(NULL) );
Run Code Online (Sandbox Code Playgroud)

在这种情况下,向下(和潜在的数据丢失)无关紧要,因为您只是使用它来为RNG播种.

  • 呃,C风格的演员阵容不属于C++程序. (2认同)
  • @aib他们更短.他们[对数字演员来说很好.](http://stackoverflow.com/a/1255015/922184) (2认同)
  • @Fabiano 你*可以*。但请记住,`srand()` 将 `unsigned int` 作为参数。如果 `unsigned int` 和 `size_t` 在你的机器上恰好是不同的大小(在 x64 上通常是这种情况),那么你会收到类似的关于潜在数据丢失的警告。所以最好坚持使用`unsigned int`。 (2认同)

Pub*_*bby 8

这条线路涉及从隐式转换time_t,其time返回到unsigned intsrand需要:

srand ( time(NULL) );
Run Code Online (Sandbox Code Playgroud)

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

srand ( static_cast<unsigned int>(time(NULL)) );
Run Code Online (Sandbox Code Playgroud)