-2

warning C4242: 'function': conversion from 'time_t' to 'unsigned int', possible loss of data

#include<stdio.h>
#include<time.h>
#include<stdlib.h>

int main(void)
{
    srand(time(0));
    int lucky = (rand() % 26) + 65;

    printf("> %d", lucky);

    return 0;
}

I am expecting the program to output a random letter between uppercase A to uppercase Z.

The srand function seems to be working with other programs but not here. Not sure why.

paddy
  • 60,864
  • 6
  • 61
  • 103

1 Answers1

2

You are instructing printf to output the value as an integer. To output a character, you need to use %c format specifier.

It is also preferable to use character constants instead of hard-coded numbers, for clarity. And, while not strictly necessary for printf, your lucky type should probably be char since you intend it to represent a character:

char lucky = (rand() % 26) + 'A';
printf("> %c", lucky);
paddy
  • 60,864
  • 6
  • 61
  • 103
  • Might be worth an edit to hammer home the point that the problem the asker is facing has absolutely nothing to do with the compiler warning. – user4581301 Mar 25 '19 at 21:25
  • This is just me trying different things, sorry new to this. – mattmallow Mar 25 '19 at 21:55
  • But what bothers me is the error:"error C2220: warning treated as error - no 'object' file generated" which is indicating that my "srand(time(0))" is wrong? I believe it doesn't have anything wrong with the rest of the code? – mattmallow Mar 25 '19 at 21:56
  • Regarding "warning treated as error", yes that's an issue for you. It will cause compilation to fail if any warnings are encountered. Generally, it's a good idea to keep this enabled because warnings are there for a reason. Just fix the warning, which you can do after reviewing the question that was referenced as already providing an answer. – paddy Mar 25 '19 at 21:59
  • @paddy Cheers, thanks for that. – mattmallow Mar 25 '19 at 22:00