0

Possible Duplicate:
Generate a random number within range?

I am trying to make it so when the code is executed, I can type the max number in command prompt to redefine the max number and generate a new random number inbetween 0 and new Max number.

Did I do this correctly?

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


int main()
{
    int randomnumber ;
    int max;
    srand( time(NULL) );
    scanf("Enter total number of students %d",&max);
    randomnumber=rand()% 30;
    printf("This is your random number\n %d",randomnumber);
    getchar();
    return 0;
}
Community
  • 1
  • 1
Tohrik
  • 11
  • 1
  • 1

1 Answers1

1

You've used the scanf to send a message to the user, but you need to use printf for that. Try:

printf("%s", "Enter total number of students: ");
scanf("%d",&max);

You can then change the %30 to %max to give the user a number between 0 and max - 1.

randomnumber=rand()% max;

As commenters have said, using modulo to reduce the range of rand() will not give you a good random distribution. Also, be sure to check that max is greater than 0, otherwise you will get an error.

If you're wondering why you're getting a large number in max at the moment, it is because you're not initializing max explicitly. With C and C++ this means that there can be junk data in there. It is not like Java or C# where an int is automatically initialized to 0.

Steve
  • 7,171
  • 2
  • 30
  • 52
  • Though worth mentioning that this will have a bias unless max divides RAND_MAX. – Frank Jan 16 '13 at 08:25
  • When I change it to %max it doesn't do what I want it to do. When I enter 20, it gives me some number way beyond 20 instead of under. – Tohrik Jan 16 '13 at 08:33
  • @Tohrik Then you did something wrong. Note that none of you are checking if scanf actually read the proper number you input, so you should make sure scanf() doesn't return an error, and while debugging, it'd also help if you print out `max` so you can make sure it is the value you think it is. – nos Jan 16 '13 at 09:07
  • Also worth noting that I/O, such as `scanf()` can fail. – unwind Jan 16 '13 at 09:07
  • I'm wondering why he put a placeholder in printf. – Tohrik Jan 17 '13 at 05:37
  • Because incorrect usage of printf can introduce [format string vulnerabilities](http://stackoverflow.com/questions/5672996/format-string-vulnerability-printf). In this case it is not strictly necessary, but I have found that specifying a placeholder is a good habit to get into as it becomes easier to spot incorrect usage. – Steve Jan 17 '13 at 07:53