我制作了一个简单的程序,允许用户选择多个骰子,然后猜出结果...我之前发布了此代码,但有一个错误的问题,因此将其删除了...现在,我对此没有任何错误甚至警告代码,但由于某种原因,此警告不断弹出,我不知道如何解决...
“警告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:“参数”:从“time_t”到“unsigned int”的转换,可能丢失数据

最佳答案

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

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

  • 因此,您会收到警告。您可以通过强制转换使其静音:
    srand ( (unsigned int)time(NULL) );
    

    在这种情况下,向下转换(以及潜在的数据丢失)无关紧要,因为您仅使用它来播种RNG。

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

    10-11 22:42
    查看更多