Im trying to make a basic game just to test my skills. I googled a function that would generate a random number in C and it seemed to work... but when trying to call the function to generate random stats for my game it seems to fail me... It spits out numbers that are either ridiculously large or ridiculously small... or just equal to zero. Heres my code, can anyone help me with this?
What is the code supposed to do? In other words, what numbers (range of numbers) do you expect?
rand() % N will generate a (pseudo) random integer between 0 and N - 1 inclusively.
For example, rand() % 100 will generate a random integer between 0 and 99.
for level it should be 1 to 3. For attack it should be 45 to 150 (in the code it says 1501 which was a mistake) for defense it should be 45 to 150. for health it should be 100 to 500. and for starting xp it should be 50 to 1000.
Haha, well I have to agree with you there. But this is really just to test what i have learned from a tutorial series I'm watching by the guys at wibit.net. They seem to be pretty set on making all there students learn C before anything else, and being someone who is fairly new I'm not really one to object. I have worked with some OO programing languages and know this would be much easier if i were to be using objects but oh well, I guess I gotta work with what I know for now and upgrade later.
And I just entered the code the way you suggested and got the same output... here is how the IF statement goes now:
I just noticed your #define has a typo at the end. Can the existence of this #define at all be explained? Are you random numbers now working as expected?
You are comparing a pointer to a char in line 22, try doing this:
1 2 3 4
// Two different ways of doing it (ONLY CHOOSE ONE)
if (*choice == 'a' || choice[0] == 'A') {
// etc.
}
This means that they are just being associated junk that happened to exist when they were declared. Why are you using a char array of size 1 anyway? Just use a single char and tell scanf that.
EDIT:
Also, you are using scanf incorrectly anyway, because you are supplying an array of at least 2 to an array of size 1 (using %s adds a null terminator to the end of the string). Use %c instead.
Thank you very much! That seems to have worked greatly! Haha and thanks for the advice on scanf as well... Still kinda new to this, so i need all the advice i can get.