Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
478 views
in Technique[技术] by (71.8m points)

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

I made a simple program that allows the user to pick a number of dice then guess the outcome... I posted this code before but with the wrong question so it was deleted... now I cannot have any errors or even warnings on this code but for some reason this warning keeps popping and I have no clue how to fix it... "warning C4244: 'argument' : conversion from 'time_t' to 'unsigned int', possible loss of data"

#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! 
";
            std::cout << "Want to try again?(Yes/No) ";
            std::cin >> decision;
        } else{
            std::cout << "Sorry, the number was " << random << "... better luck next  time 
" ;
            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(), '
' );
    return 0;
}

This is what I am trying to figure out, why am I getting this warning: warning C4244: 'argument' : conversion from 'time_t' to 'unsigned int', possible loss of data

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

That's because on your system, time_t is a larger integer type than unsigned int.

  • time() returns a time_t which is probably a 64-bit integer.
  • srand() wants an unsigned int which is probably a 32-bit integer.

Hence you get the warning. You can silence it with a cast:

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

In this case, the downcast (and potential data loss) doesn't matter since you're only using it to seed the RNG.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...